问题
I have a Component, containing a Template Driven form. What I really want to do is to add a code to routerCanDeactivate
method to check if the form is pristine
and if not, to warn the user before continuing with navigation. I know that Angular takes a Template Driven form and builds a ControlGroup. In the template, I can get to it like so: <form #hf="ngForm" ...>
Is there a way to reference it from within a component?
If this is not possible, is there another way to check if the form is dirty from routeCanDeactivate?
Thank you for the help.
回答1:
preparing the form
You need to add ngControl
to each control
<input ngControl="someName" ...>
and ngControlGroup
to each element between the inputs and the <form>
element
<div ngControlGroup="groupName">
to get your form controls collected and managed by the NgForm
directive.
referencing the form
If you only have one form in your template you can use
@ViewChild(NgForm) formA;
to get a reference to the form, otherwise add template variables to the forms
<form ngForm #formA="ngForm">
and get a reference using
@ViewChild('formA') formA;
then you can check pristine
status like
routerCanDeactivate() {
return this.form.pristine;
}
Plunker example
来源:https://stackoverflow.com/questions/36583078/how-to-get-reference-to-angular-built-controlgroup-from-within-a-component