子窗体脏时从父组件访问子组件

Access from parent component to child component when the child form is dirty

我创建了一个挂起的更改警卫,如果对表单进行了更改,它会提醒我的用户,并在离开之前警告他们。

一切正常,但我在页面上有一个使用选择器呈现的子组件,该组件也有一个表单。

我如何从我的守卫处访问此表格以检查表格是否有问题?

后卫:

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);
    }
}

将 parent 表单作为输入传递给 child 组件。然后 child 组件需要将输入字段绑定到该表单。如果 child 的输入字段变脏,那么 parent 表单也会变脏。所以你不需要在你的守卫中访问 child 表格。例如,

Parent 组件 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({});
    }
}

Parent 组件的 HTML

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

Child 组件 ts

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

Child 组件的 HTML

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