I am looking to develop a dynamic form builder using Angular 8.
In this form builder, I want to create inputs with dynamic validations. The input and validation fields must be customizable and dynamic.
This is how I initialized the form:
createItem(): FormGroup {
return this.formBuilder.group({
type: ['', Validators.compose([Validators.required])],
label: ['', Validators.compose([Validators.required])],
inputType: ['', Validators.compose([Validators.required])],
name: ['', Validators.compose([Validators.required])],
formName: ['', Validators.compose([Validators.required])],
validations: this.formBuilder.group({
name: [''],
message: [''],
validator: ['']
})
});
}
initialFormBuilder(): void {
this.formGroup = this.formBuilder.group({
formItem: this.formBuilder.array([this.createItem()])
});
}
validationItem(): FormGroup {
return this.formBuilder.group({
name: [''],
message: [''],
validator: ['']
});
}
addItem(): void {
this.items = this.formGroup.get('formItem') as FormArray;
this.items.push(this.createItem());
}
addValidation(): void {
this.validationItems = this.formGroup.get('formItem').get('validations') as FormArray;
this.validationItems.push(this.validationItem());
}
Here's the HTML code:
<form [formGroup]="formGroup">
<div formArrayName="formItem" *ngFor="let item of formGroup.get('formItem').controls; let i = index;">
<div [formGroupName]="i">
...
</div>
</div>
</form>
When I added the line below, an error occurred:
<div formArrayName="validations" *ngFor="let validation of formGroup.get('formItem').get('validations').controls; let j = index">
I want users to be able to add new validations by clicking on a button. How can I fix this issue?