Angular 检测表单变化

Angular detect the form change

我有一个包含一些字段的模板驱动表单。在某些条件评估为真之前,此表单不会显示。我希望在任何这些字段的值发生变化时得到通知。所以我有以下代码:

HTML:

<form *ngIf="aCondition" #myForm="ngForm">
...
</form>

组件:

@ViewChild('myForm') myForm: NgForm

aCondition: boolean = false;

ngOnInit() {
    this.myForm.form.valueChanges.subscribe(...);
}

changeCondition() {
    this.aCondition = true;
    this.myForm.form.valueChanges.subscribe(...);
}

但是在两个 event/function 中,this.myFormundefined。有什么想法吗?

当您将 *ngIf 附加到一个元素并且计算结果为 false 时,它甚至不会在 DOM 中呈现。这意味着它不会作为 ViewChild 被拾取,因此将保持未定义状态。

关于 ViewChild 的另一件事是在 AfterViewInit 生命周期钩子之前不会拾取任何东西,所以任何时候你需要附加一些东西到 ViewChild,在 ngAfterViewInit 以确保它在那里。

要使用 ngIf 获取 ViewChild 的引用,您必须使用 setter,当条件为真实

private myForm: NgForm;

@ViewChild('myForm') set formRef(formRef: NgForm) {
 this.myForm= formref;
}