Reputation: 89
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"
}
]
Upvotes: 2
Views: 2775
Reputation: 657
Here is your code edited https://stackblitz.com/edit/angular-ivy-bzfjvw
I added two lines in your .ts code. First, if the category value equals 3, I call the addGroup function, because you want to start with the first item without clicking.
But, this part is important, if the category is different than 3, we are going to clean the timesArray, deleting all the elements, because if not, when you select category 3 again, it will be 2 elements at the beginning.
The second part, in your .html code I added an * ngIf on line 29. The Delete text field is going to show only if it has more than one element.
Upvotes: 3