该问题的原因是,在FormArray中创建另一个FormArray时,内部的FormControl没有被正确设置。解决方法是使用setValue()函数手动为内部FormControl设置值。
以下是在Angular中解决该问题的示例代码:
创建了两个子FormArray:
form = this.fb.group({ children: this.fb.array([ this.fb.group({ child1: [null], child2: this.fb.array([ this.fb.group({ child21: [null], child22: [null] }) ]) }) ]) });
当需要在FormArray中动态添加一些值时,如果没有设置Child21的值,则会出现问题:
this.form.get('children').push( this.fb.group({ child1: [null], child2: this.fb.array([this.fb.group({child22: [null]})]) }) );
为了解决这个问题,只需将setValue()函数添加到child21 FormControl中:
this.form.get('children').push( this.fb.group({ child1: [null], child2: this.fb.array([this.fb.group({child21: [null], child22: [null]})]) }) ); this.form .get('children') .at(this.form.get('children').length - 1) .get('child2') .setValue([{child21: 'value21', child22: 'value22'}]);