I have a form with following fields: name (textbox), category(dropdown). I want to display a formarray with an add option on selection of dropdown="3". When I click on "add new textfields", new textboxes should be added. Also need to enable or disable the form array based on dropdown as it should not affect validations
Right now I'm showing a textbox (listitem) after selection of dropdown="3". and then on addnewtextfield I'm calling a formarray.(need to remove this).
Please help me achieve the functionality. Thanks in advance.
<select class="Dropdown" formControlName="category">
<option value="undefined" selected disabled >Select Category</option>
<option *ngFor="let list of dropdownitems" [value]="list.id" >{{list.name}}</option>
</select>
<ng-container *ngIf="showarray">
<input type="text" formControlName="listItem" class="form-control" >
<a (click)="addGroup()">Add New Textfield</a>
</ng-container>
<ng-container formArrayName="times">
<span *ngFor="let time of timesArray.controls; let i = index;">
<span [formGroupName]="i">
<input type="text" class="form-control" formControlName="lists" placeholder="enter dropdown options">
</span>
<a (click)="removeGroup(i)">Remove Textfield</a>
</span>
</ng-container>
here is where i disabled or enabled code.
ngOnInit(): void {
this.addForm = this.formBuilder.group({
name: ['', [Validators.required, Validators.pattern('[a-zA-Z# ]*')]],
times: this.formBuilder.array([])
});
}
adding/ removing form array code
addGroup() {
if (this.addForm.get('listItem').invalid)
{
alert ("fill the term field")
this.addForm.get('listItem').updateValueAndValidity()
return;
}
if (this.timesArray.invalid)
{
alert ("fill the items field")
this.timesArray.updateValueAndValidity()
return;
}
const val = this.formBuilder.group({
lists: ['', Validators.required],
});
const form = this.addForm.get('times') as FormArray;
form.push(val);
}
removeGroup(index) {
const form = this.addForm.get('times') as FormArray;
form.removeAt(index);
}
i want the formarray format to be like below
"times": [
{
"lists": "ssssssssssss"
},
{
"lists": "sssssssssss"
},
{
"lists": "ssssssssssss"
}
]