简体   繁体   English

Angular - 在页面加载时多次调用 NgForm valueChanges

[英]Angular - NgForm valueChanges called multiple times on page load

I have a problem using the valueChanges function of ngForm.我在使用 ngForm 的 valueChanges function 时遇到问题。 When binding an Input variable to the form with [(ngModel)], the form gets called multiple times on page load.当使用 [(ngModel)] 将输入变量绑定到表单时,表单会在页面加载时被多次调用。

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

}

Perhaps it will be sufficient to just check for dirty/touched state也许只检查脏/触摸 state 就足够了

From: https://angular.io/guide/form-validation来自: 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".

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

}

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 {

  }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM