[英]how to use can-deactivate without routing
我的問題是我有一個父組件和一個子組件。父組件有表單,子組件有表單。 所有子組件都共享父組件的同一路由,子組件沒有任何路由器鏈接來唯一標識。 所以任務是在表單臟並且用戶導航離開該頁面時顯示彈出窗口。所以我實現了可以停用防護。 所以在“app.module.ts”中,我如何為子組件提供can-deactivate(因為子組件沒有任何路由器路徑)。 我怎樣才能做到這一點? 檢測未保存的更改和顯示彈出窗口的任何替代方法?請幫助我
Noway,它最初是為處理路由而設計的。
據我了解,父子窗體是完全獨立的。 因此,您可以在沒有任何 URL 的情況下定義子組件並在那里放置一個守衛。 見下面的實現。
父組件.ts
@Component({
selector: 'parent-component',
template: `
<form>
<input type="text" />
<input type="text" />
</form>
//
<!-- Here will be your child component -->
<router-outlet></router-outlet>
`,
changeDetection: ChangeDetectionStrategy.OnPush
})
class ParentComponent {
//... your parent form config
public form: FormGroup = new FormGroup({});
canDiscardChanges() {
const { valid, pristine } = this.form;
return valid || pristine;
}
}
子組件.ts
@Component({
selector: 'child-component',
template: `
<form>
<input type="text" />
<input type="text" />
</form>
`,
changeDetection: ChangeDetectionStrategy.OnPush
})
class ChildComponentWithForms {
//... your child form config
public form: FormGroup = new FormGroup({});
canDiscardChanges() {
const { valid, pristine } = this.form;
return valid || pristine;
}
}
app-routing.module.ts
@NgModule({
imports: [
RouterModule.forChild([
{
path: 'parent-route',
component: ParentComponent,
canDeactivate: [DiscardChangesGuard],
children: [
{
path: '',
component: ChildComponentWithForms,
canDeactivate: [DiscardChangesGuard]
}
]
}
])
],
exports: [RouterModule]
})
export class AppRoutingModule {}
丟棄-changes.guard.ts
import { Observable, of } from 'rxjs';
import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';
@Injectable({ providedIn: 'any' })
export class DiscardChangesGuard implements CanDeactivate<IDiscardChanges> {
canDeactivate(component: IDiscardChanges) {
if (component.canDiscardChanges instanceof Function) {
return component.canDiscardChanges();
}
return of(true);
}
}
export interface IDiscardChanges {
canDiscardChanges(): Observable<boolean> | Promise<boolean> | boolean;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.