【问题标题】:Angular - NgForm valueChanges called multiple times on page loadAngular - 在页面加载时多次调用 NgForm valueChanges
【发布时间】:2020-09-24 11:26:00
【问题描述】:

我在使用 ngForm 的 valueChanges 函数时遇到问题。当使用 [(ngModel)] 将输入变量绑定到表单时,表单会在页面加载时被多次调用。

有没有一种只检测用户更改的好方法?

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

}

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

    试试这个:

    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 {
    
      }
    
    }
    

    【讨论】:

      【解决方案2】:

      我解决了这个问题:

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

      【讨论】:

        【解决方案3】:

        也许只检查脏/触摸状态就足够了

        发件人: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".
        

        【讨论】:

        • 为我解决了这个问题。非常感谢!
        猜你喜欢
        • 2021-01-12
        • 2017-12-24
        • 2017-05-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多