可以使用valueChanges和subscribe方法来监听formControl的值是否发生变化。在onFocusOut事件中,通过调用markAsDirty方法来标记表单已被修改。示例代码如下:
component.ts:
import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
@Component({
selector: 'app-root',
template: `
`
})
export class AppComponent implements OnInit {
nameControl = new FormControl();
ngOnInit() {
// Watch for changes to the name control value
this.nameControl.valueChanges.subscribe(value => {
console.log('Value changed:', value);
});
}
onFocusOut() {
// Mark the form as dirty (if the value has changed)
if (this.nameControl.dirty) {
console.log('Form is dirty');
}
}
}
component.html: