简体   繁体   English

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

[英]Access from parent component to child component when the child form is dirty

I have created a pending changes guard which alerts my users, if there has been changes made to the form and warns them before navigating away. 我创建了一个待处理的变更防护,如果对表单进行了更改,它会警告我的用户,并在导航前警告他们。

This all works fine but I have a child component on the page which is rendered using a selector, this component has a form on also. 一切正常,但是我在页面上有一个使用选择器呈现的子组件,该组件也有一个表单。

How can I access this form from my guard to check if the form is dirty? 我如何从我的门卫那里访问此表格,以检查该表格是否脏了?

Guard: 守护:

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

Pass the parent form as input to child component. 将父表单作为输入传递给子组件。 Then child component needs to bind the input field to that form. 然后,子组件需要将输入字段绑定到该表单。 If child's input fields becomes dirty, then parent form will become dirty. 如果孩子的输入字段变脏,则父表单将变脏。 So in that you do not need to access child form in your guard. 因此,您无需在监护人中访问子表格。 For example, 例如,

Parent Component 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 Component's HTML 父组件的HTML

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

Child Component ts 子组件ts

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

Child Component's HTML 子组件的HTML

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM