Search code examples
angularangular-forms

Angular detect the form change


I have a template driven form with some fields. This form won't show up until some condition evaluates to true. And I would like to get notified when the value of any of those fields changes. So I have the following code:

The HTML:

<form *ngIf="aCondition" #myForm="ngForm">
...
</form>

The component:

@ViewChild('myForm') myForm: NgForm

aCondition: boolean = false;

ngOnInit() {
    this.myForm.form.valueChanges.subscribe(...);
}

changeCondition() {
    this.aCondition = true;
    this.myForm.form.valueChanges.subscribe(...);
}

But in both event/function, this.myForm is undefined. Any ideas?


Solution

  • When you attach *ngIf to an element and that evaluates to false, then it won't even be rendered in the DOM. That means it won't be picked up as a ViewChild, and so will remain undefined.

    Another thing to remember about ViewChild is that won't pick anything up until the AfterViewInit lifecycle hook, so any time you need attach something to a ViewChild, do it inside of ngAfterViewInit to make sure it's there.