我有一个人课。
export class Person {
public name: Name;
public childList: Person[];
public string: gender;
// Other Attribute
constructor(person?)
{
person = person || {};
this.name = person.name || {};
this.gender = person.gender || {};
this.childList = person.childList || [{}];
}
}
和Name类包含:
export class Name {
public firstName?: string;
public lastName?: string;
constructor(name?)
{
name = name || {};
this.firstName = name.firstName || null;
this.lastName = name.lastName || null;
}
}
人员组成部分的一部分是:
createChildInfoForm() {
this.childInfoForm = this.formBuilder.group({
childList: this.formBuilder.array([]),
});
}
insertChildInfoForm() {
this.setChildren(this.employee.childList);
}
get childList(): FormArray {
return this.childInfoForm.get('childList') as FormArray;
}
setChildren(children: Person[]) {
const childFGs = children.map(child => this.formBuilder.group(child));
const childFormArray = this.formBuilder.array(childFGs);
this.childInfoForm.setControl('childList', childFormArray);
}
addChild() {
this.childList.push(this.formBuilder.group(new Person()));
}
removeChild(i: number) {
const control = <FormArray>this.childInfoForm.controls['childList'];
control.removeAt(i);
}
现在HTML是:
<div formArrayName="childList" class="well well-lg">
<div *ngFor="let child of childList.controls; let i=index" [formGroupName]="i" >
<fieldset>
<legend>Child # {{i + 1}}
<mat-icon style="font-size: 15px; padding-left: 5px" *ngIf="childInfoForm.controls.childList.controls.length > 1" (click)="removeChild(i)">cancel</mat-icon>
</legend>
<!-- The repeated child template -->
<div formGroupName="name"> <!-- Cannot find control with path: 'childList -> 0 -> name -> firstName' -->
<mat-form-field class="w-100-p" fxFlex="100">
<input matInput formControlName="firstName" placeholder="Child Name">
</mat-form-field>
</div>
<mat-form-field class="w-100-p" fxFlex="100"> <!-- Its Working -->
<input matInput formControlName="gender" placeholder="Child Name">
</mat-form-field>
</fieldset>
<br/><br/>
<!-- End of the repeated address template -->
</div>
<button mat-raised-button class="save-employee-button mat-white-bg mt-16 mt-sm-0" (click)="addChild()">
<span>Add CHILD</span>
</button>
</div>
当我点击“添加儿童按钮”时,会添加一个新表格。但错误是
找不到路径控件:'childList - &gt; 0 - &gt;名字 - &gt;的firstName”。
但对于'性别'的人 - &gt;性别正在发挥作用我不确定为什么formGroupName不能在Name对象上工作。
如何获得名称 - &gt; HTML中的firstName?
我是Angular的初学者。
答案 0 :(得分:0)
您不能this.childList.push(this.formBuilder.group(new Person()));
,因为您拥有name
类<{1}}属性的嵌套formGroup
Person