Angular - FormGroup 上的 ngOnChange

Angular - ngOnChange on FormGroup

我需要检测 FormGroup 字段的实时变化。我有一个简单的父子组件结构如下:

父组件视图

<my-child [myForm]="myForm"></my-child>

子组件控制器

@Input()
myForm: FormGroup;

ngOnChanges(changes: SimpleChanges) {
console.log('changes', changes)
}

问题是当表单域发生变化时没有检测到任何变化。有没有办法触发 ngOnChanges 任何形式的变化? 谢谢。

您可以使用以下内容:

this.myForm.valueChanges.subscribe(changes => {
    // do what you need with the form fields here
    // you can access a form field via changes.fieldName
});
formName: FormGroup;      
@Input() myForm: FormGroup;

ngOnChanges(changes: SimpleChanges) {
    const MyFormChanges: SimpleChange = changes.myForm;
    // To Check current values
    console.log(MyFormChanges.currentValue)

    // To Check previous values
    console.log(MyFormChanges.previousValue)

    // To Set Current Values to fields using controls
 this.formName.controls['email'].setValue(MyFormChanges.currentValue.email);
}