简体   繁体   中英

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,

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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