Reputation: 489
I wonder if it possibile to access statusChanges
in Angular 2 Template driven forms.
I tried the approach offered by this answer, but it doesn't work. https://stackoverflow.com/a/49666202/6920871
Should I refactor the form as Reactive or can I use another approach to emit an event when form validation status changes?
__
Current approach that does not work:
In component TS
export class FormComponent implements OnInit {
[...]
@ViewChild('myForm', { static: false }) myForm;
ngAfterViewInit() {
let c = this.myForm.statusChanges.subscribe(() => {
console.log(this.myForm.status, "Is form dirty yet: " + this.myForm.dirty);
});
}
in component template
<form #myForm>
[...]
</form>
I get a ERROR TypeError: Cannot read property 'subscribe' of undefined
at FormComponent.ngAfterViewInit (form.component.ts:27)
(also this.myForm
is defined, but no property statusChanges
)
Upvotes: 1
Views: 649
Reputation: 691755
The problem is that you're getting the reference to the element named myForm, instead of getting a reference to the NgForm directive hosted by this element.
Change 'myForm'
to NgForm
, or use the read: NgForm
option.
@ViewChild('myForm', { read: NgForm, static: false })
myForm: NgForm;
ngAfterViewInit() {
this.myForm.statusChanges.subscribe(e => console.log('status changed: ' + e));
}
Also note that your component should implement AfterViewInit
.
Upvotes: 3