我按照网站链接https://scotch.io/tutorials/how-to-build-nested-model-driven-forms-in-angular-2中的教程,制作了一个能够添加多个表单控件并且运行良好的反应式表单。我按照教程中的指导将嵌套的表单控件移动到一个单独的组件中,我需要从父组件访问formarray的索引值。我希望这个索引值设置为formconrols中的一个默认值,这是我在plnkr中的代码, http://plnkr.co/edit/ZjEuBWrmJDiRmP4FeCzv?p=preview
我的分离日和描述组件,
import { Component, Input } from '@angular/core';
import { FormArray, Validators, FormGroup } from '@angular/forms';
@Component({
selector: 'day-and-daydescription',
template: ` <div [formGroup]="formGroup">
<div class="form-group col-xs-4" >
<label for="text">Day</label>
<input type="text" class="form-control" formControlName="day" [ngModel]="group.i + 1" readonly>
</div>
<!--Day Description-->
<div class="form-group col-xs-4">
<label>Description</label>
<input type="text" class="form-control" formControlName="description">
</div>
<div>`
})
export class DayAndDescriptionComponent {
@Input('group')
public formGroup: FormGroup;
}
请查看plunker中的整个代码。
答案 0 :(得分:2)
正如您自己注意到的,您可以从父级操作整个表单,无需尝试从子级访问索引。你在父母的表格中所做的一切都会反映在孩子身上。
关于错误:
检查后表情发生了变化。
这是正常的,在开发模式下发生。摘录自Expression ___ has changed after it was checked:
简而言之,当处于开发模式时,每一轮更改检测都会立即跟随第二轮,以验证自第一轮结束以来没有任何绑定发生更改,因为这表明更改是由更改检测本身引起的。
导致此问题的是孩子的实际@Input
。您可以手动触发更改检测,此错误将消失。由于我们正在处理@Input
,您可以在ngOnChanges
:
constructor(private ref: ChangeDetectorRef) { }
ngOnChanges() {
this.ref.detectChanges()
}