1
votes

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)

1
If you want more programmatic control over your form, I'd strongly suggest switching to reactive forms.skolldev
@xdecdec it's a huge refactor of a form other people are working on and I wonder if I can avoid the refactor.christo
Define "doesn't work". Post a complete minimal example reproducing the problem.JB Nizet

1 Answers

2
votes

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

Demo

Also note that your component should implement AfterViewInit.