typescript Angular2:检测表单变化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43793818/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:30:45  来源:igfitidea点击:

Angular2: Detect form changes

angulartypescriptangular2-forms

提问by Vingtoft

In Angular2 4.0 I have a FormGrouplooking like this:

在 Angular2 4.0 中,我FormGroup看起来像这样:

this.form = this._fb.group({
      a: ['', [Validators.required]],
      b: ['', [Validators.required]],
      c: ['', [Validators.required]],
    });

Is it possible to subscribe valueChangedon individual fields?

是否可以订阅valueChanged单个字段?

I dont want to detect changes on input c, so the below approach does not work:

我不想检测 input 的变化c,所以下面的方法不起作用:

this.form.valueChanges.debounceTime(400).subscribe(data => {
     // Do something
    });

回答by tottomotto

You can add separate subscriptions for FormControl aand b.

您可以为 FormControl ab添加单独的订阅。

this.heroForm.controls["a"].valueChanges.subscribe(data => {
 // Do something
});

this.heroForm.controls["b"].valueChanges.subscribe(data => {
 // Do something
});

回答by Sujith S

  
//get form ref  
@ViewChild('myForm') myForm;

//implement afterview init to your class and use
// or you can use same code with ngOnInit

ngAfterViewInit(){
  this.myForm.valueChanges.debounceTime(500).subscribe(data =>            console.log('Form changes', data));
}

You can use this code, it will give you changed field data also.

您可以使用此代码,它也会为您提供更改的字段数据。