这种情况下,通过手动引用变更检测器来解决这个问题。即,在需要加载的控件数组中使用ChangeDetectorRef服务的detectChanges()方法。示例如下:
HTML模板:
组件代码:
import { Component, ChangeDetectorRef } from '@angular/core';
import { FormGroup, FormControl, FormArray } from '@angular/forms';
@Component({
selector: 'my-app',
template: ''
})
export class AppComponent {
myForm: FormGroup;
constructor(private cd: ChangeDetectorRef) {
this.myForm = new FormGroup({
myArray: new FormArray([new FormControl('')])
});
}
addItem() {
(this.myForm.get('myArray') as FormArray).push(new FormControl(''));
this.cd.detectChanges();
}
}
在addItem()方法中,手动调用变更检测器的detectChanges()方法来更新视图,从而在表单中正确加载新的控件。