Angular2:检测表单变化
Angular2: Detect form changes
在 Angular2 4.0 中,我有一个 FormGroup
看起来像这样:
this.form = this._fb.group({
a: ['', [Validators.required]],
b: ['', [Validators.required]],
c: ['', [Validators.required]],
});
是否可以在个别领域订阅 valueChanged
?
我不想检测输入的变化 c
,所以下面的方法不起作用:
this.form.valueChanges.debounceTime(400).subscribe(data => {
// Do something
});
您可以为 FormControl a 和 b 添加单独的订阅。
this.heroForm.controls["a"].valueChanges.subscribe(data => {
// Do something
});
this.heroForm.controls["b"].valueChanges.subscribe(data => {
// Do something
});
//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.
this.form.valueChanges
.pipe(
debounceTime(500), // Wait for 0.5
distinctUntilChanged() // execute only if a different value is emitted
)
.subscribe((newForm) => {
console.log(newForm);
});
在 Angular2 4.0 中,我有一个 FormGroup
看起来像这样:
this.form = this._fb.group({
a: ['', [Validators.required]],
b: ['', [Validators.required]],
c: ['', [Validators.required]],
});
是否可以在个别领域订阅 valueChanged
?
我不想检测输入的变化 c
,所以下面的方法不起作用:
this.form.valueChanges.debounceTime(400).subscribe(data => {
// Do something
});
您可以为 FormControl a 和 b 添加单独的订阅。
this.heroForm.controls["a"].valueChanges.subscribe(data => {
// Do something
});
this.heroForm.controls["b"].valueChanges.subscribe(data => {
// Do something
});
//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.
this.form.valueChanges
.pipe(
debounceTime(500), // Wait for 0.5
distinctUntilChanged() // execute only if a different value is emitted
)
.subscribe((newForm) => {
console.log(newForm);
});