Angular中的表单控件有一个valueChange属性。这个属性返回一个Observables对象,我们可以订阅它以获取表单控件值的变化。
import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponent implements OnInit {
myControl = new FormControl();
ngOnInit() {
this.myControl.valueChanges.subscribe(value => {
console.log('Value changed:', value);
});
}
}
在上面的例子中,我们创建了一个FormControl对象来表示表单中的一个输入框,并使用valueChanges属性来监听它的变化。当用户在Input框中输入文本时,控制台将记录每次值更改的内容。
使用valueChanges属性能够非常方便地检测表单控件属性的变化,配合RxJS操作符使用也可以实现诸如过滤、节流和去抖等功能。