0

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 Answers 3

2

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".
Sign up to request clarification or add additional context in comments.

1 Comment

Solved the problem for me. Thanks a lot!
1

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

}

Comments

0

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 {

  }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.