Reputation: 847
i need to create a dynamic form . when click AddNew
it create a new form .
i using this code in ts
file :
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);
}
and use this in 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>
but when i click it how me this Error :
AddinfoComponent.html:21 ERROR TypeError: Cannot read property 'push' of null at AddinfoComponent.push../src/app/admin/admin/dashboard/productinfo/addinfo/addinfo.component.ts.AddinfoComponent.AddInfoName (addinfo.component.ts:41)
How Can i solve this problem ?
Upvotes: 0
Views: 59
Reputation: 3451
wrong name should be infoName
public InfoForm() {
this.addinfoForm=this.fb.group({
infoName:this.fb.array([this.CreateInfoName()])
})
this.infoNameList=this.addinfoForm.get('infoName') as FormArray; // <- previously infoNames
}
Upvotes: 1
Reputation: 1525
Maybe get('infoName')
instead of get('infoNames')
?
public InfoForm() {
this.addinfoForm=this.fb.group({
infoName:this.fb.array([this.CreateInfoName()])
})
this.infoNameList=this.addinfoForm.get('infoName') as FormArray;
}
Upvotes: 1
Reputation: 8183
The problem is that your infoNameList
property has been declared, but not initialised so it's null.
Just do the following:
ngOnInit() {
this.inforNameList = this.fb.array([])
this.InfoForm();
}
Upvotes: 1