0
votes

I have a problem using the valueChanges function of ngForm. When binding an Input variable to the form with [(ngModel)], the form gets called multiple times on page load.

Is there a good way to only detect user changes?

export class ContainerComponent implements OnInit, AfterViewInit {
  @Input() formData: Object;
  @ViewChild('form') form: NgForm;
  constructor() { }

  ngOnInit(): void {
  }

  ngAfterViewInit(): void {
     this.form.form.valueChanges.subscribe((value) => {
       //Gets called multiple times on page load
     });
  }

}
3

3 Answers

2
votes

Perhaps it will be sufficient to just check for dirty/touched state

From: https://angular.io/guide/form-validation

To prevent the validator from displaying errors before the user has a chance to edit the form, you should check for either the dirty or touched states in a control.

When the user changes the value in the watched field, the control is marked as "dirty".
When the user blurs the form control element, the control is marked as "touched".
1
votes

I solved the problem:

export class ContainerComponent implements OnInit, AfterViewInit {
  @Input() formData: Object;
  @ViewChild('form') form: NgForm;
  constructor() { }

  ngOnInit(): void {
  }

  ngAfterViewInit(): void {
     this.form.form.valueChanges.subscribe((value) => {
       if(this.form.form.dirty) {
          //DO STUFF
        }
     });
  }

}
0
votes

Try this :

export class ContainerComponent implements OnInit, AfterViewInit {
  @Input() formData: Object;
  @ViewChild('form') form: NgForm;
  constructor() { }

  ngOnInit(): void {
   this.form.form.valueChanges.subscribe((value) => {
       //Gets called multiple times on page load
     });
  }

  ngAfterViewInit(): void {

  }

}