1

我创建了一个挂起的更改后卫它提醒我的用户,如果有一直形式所做的更改,并就离开了警告他们。访问时子窗体脏

这一切都很好,但我有一个页面上使用选择器呈现的子组件,该组件也有一个窗体。

如何从我的警卫访问此表格以检查表格是否脏?

后卫:

import { CanDeactivate } from '@angular/router'; 
import { FormGroup } from '@angular/forms'; 
import { DialogService } from "ng2-bootstrap-modal"; 
import { ConfirmComponent } from '../components/confirm/confirm.component'; 
import { Inject } from '@angular/core'; 

export interface FormComponent { 
    form: FormGroup; 
} 

export class PreventUnsavedChangesGuard implements CanDeactivate<FormComponent> { 

constructor(@Inject(DialogService) private dialogService: DialogService) { } 

canDeactivate(component: FormComponent): Promise<boolean> { 

    if (component.form.dirty) { 
     return new Promise<boolean>((resolve, reject) => { 

      this.dialogService.addDialog(ConfirmComponent, { 
       title: 'Unsaved Changes', 
       message: 'You have unsaved changes. Are you sure you want to navigate away?' 
      }) 
       .subscribe((isConfirmed) => { 
        return resolve(isConfirmed); 
       }); 
     }); 
    } 

    return Promise.resolve(true); 
    } 
} 
+0

无论是子组件在应用程序中的其他一些地方习惯? –

+0

如果没有在其他地方使用,则从子组件中移除'form',并在子组件内使用父组件'form'。通过这种方式,如果子中的输入字段变脏,则父母也会变脏。 –

+0

@SameerK你可以通过使用孩子内部的父母compoent来解释更多你的意思吗? –

回答

2

传递父窗体输入到子组件。然后,子组件需要将输入字段绑定到该表单。如果孩子的输入字段变脏,则父表格将变脏。因此,你不需要看守孩子的形式。例如,

父组件TS

import {FormBuilder, FormGroup} from "@angular/forms"; 
private addEmailItemForm : FormGroup; 
export class ParentComponent implements OnInit, OnDestroy { 

    constructor(private _fb: FormBuilder) {} 

    ngOnInit() { 
     this.parentComponentForm = this._fb.group({}); 
    } 
} 

父组件的HTML

<child-component 
    [parentForm]="parentComponentForm" 
</child-component> 

辅元件TS

export class ChildComponent implements OnInit { 
    @Input() parentForm: FormGroup;  
    let inputFieldControl = new FormControl('', Validators.required); 
    this.parentForm.addControl(this.inputFieldControlName, inputFieldControl); 
} 

子组件的HTML

<input type="text" class="form-control" [formControl]="parentForm.controls[inputFieldControlName]">