我需要创建一个动态表格。当点击AddNew
时,它将创建一个新表单。
i在ts
文件中使用此代码:
addinfoForm:FormGroup;
infoNameList:FormArray;
infoModel:Productdetail;
constructor(private fb:FormBuilder,private router:Router,private tokenService:TokenstoreService) { }
ngOnInit() {
this.InfoForm();
}
/**
* AddInfoForm
*/
public InfoForm() {
this.addinfoForm=this.fb.group({
infoName:this.fb.array([this.CreateInfoName()])
})
this.infoNameList=this.addinfoForm.get('infoNames') as FormArray;
}
public CreateInfoName():FormGroup{
return this.fb.group({
infoName:['',Validators.compose([Validators.required])]
});
}
public AddInfoName(){
this.infoNameList.push(this.CreateInfoName());
}
public RemoveInfoName(index:number){
this.infoNameList.removeAt(index);
}
并在html中使用它:
<div class="panel-content">
<form class="form-line" [formGroup]="addinfoForm" (ngSubmit)="AddRole()">
<div formArrayName="infoNameList">
<div class="description" *ngFor="let name of addinfoForm.controls; let NameIndex=index" [formGroupName]="NameIndex">
<div [formGroupName]="i" class="row">
<label class="form-line"> Name: </label>
<input style="margin-right: 50px;" class="form-line" pInputText id="pFaName" formControlName="Name">
<app-filederrors [form]="addinfoForm"
field="pFaName"
nicename="Name">
</app-filederrors>
</div>
</div>
</div>
</form>
<button (click)="AddInfoName()">Add New </button>
<div class="button">
<button pButton type="button" label="REgister" (click)="AddCat()" [disabled]="!addinfoForm.valid" class="ui-button-rounded"></button>
<button pButton type="button" label="Cencel" class="ui-button-rounded ui-button-danger"></button>
</div>
</div>
但是当我单击它时,如何显示此错误:
AddinfoComponent.html:21错误TypeError:无法读取null的属性“ push” 在AddinfoComponent.push ../ src / app / admin / admin / dashboard / productinfo / addinfo / addinfo.component.ts.AddinfoComponent.AddInfoName(addinfo.component.ts:41)
我如何解决此问题?
答案 0 :(得分:1)
问题在于您的infoNameList
属性已经声明,但尚未初始化,因此为空。
只需执行以下操作:
ngOnInit() {
this.inforNameList = this.fb.array([])
this.InfoForm();
}
答案 1 :(得分:1)
也许是get('infoName')
而不是get('infoNames')
?
public InfoForm() {
this.addinfoForm=this.fb.group({
infoName:this.fb.array([this.CreateInfoName()])
})
this.infoNameList=this.addinfoForm.get('infoName') as FormArray;
}
答案 2 :(得分:1)
错误名称应为infoName
public InfoForm() {
this.addinfoForm=this.fb.group({
infoName:this.fb.array([this.CreateInfoName()])
})
this.infoNameList=this.addinfoForm.get('infoName') as FormArray; // <- previously infoNames
}