I want to design a dynamic form that creates a new form when the AddNew
button is clicked.
In my TypeScript (ts
) file, I have the following code:
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);
}
I have used this code in the HTML as well:
<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>
However, upon clicking the button, I encounter the following 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)
What is the best way to resolve this issue?