Reputation: 89
I have a form, inside the form I'm showing a textbox on selecting the dropdown I'm calling a form array, where i get multiple textboxes. When i submit my form is showing invalid even when i give values for all fields.
<input type="text" class="form-control" placeholder="Type" formControlName="type">
<select class="Dropdown" formControlName="category" >
<option >Select Category</option>
<option *ngFor="let list of dropdownitems" [value]="list.id" >{{list.name}}</option>
</select>
<ng-container *ngIf="optionValue == '3'">
<input type="text" formControlName="listItem" class="form-control" placeholder="enter dropdownlist items">
<small class="errormessage" *ngIf="submitted && addForm.controls.listItem.hasError('required')">
Category is required
</small>
<a (click)="addGroup()">Add New Textfield</a>
</ng-container>
<span formArrayName="times" *ngFor="let time of addForm.controls.times?.value; let i = index;">
<span [formGroupName]="i">
<input type="text" class="form-control" formControlName="lists" placeholder="enter dropdown options">
</span>
In ts i'm validating all the fields. onSubmit() function, if the form is invalid i'm showing an alert. Please correct my code and help me achieve this functionality.
ngOnInit(): void {
this.addForm = this.formBuilder.group({
name: ['', [Validators.required, Validators.pattern('[a-zA-Z# ]*')]],
times: this.formBuilder.array([])
});
console.log(this.addForm.value);
}
public dropdownitems = [{
name: "A",
id: 1
},{
name: "B",
id: 2
},{
name: "B",
id: 3
},{
name: "D",
id: 4
}]
onSubmit(){
this.submitted = true;
if (this.addForm.invalid) {
alert ('Please fill up complete details');
return;
}
console.log(this.addForm.value);
}
value = this.formBuilder.group({
lists: ['', Validators.required],
});
addGroup() {
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);
}
}
Upvotes: 1
Views: 785
Reputation: 3243
The problem is that even if the fields are hidden in the template (HTML
) they are defined in the form as required
.
You need to either add and remove the form fields conditionally or you need to make them enabled
/ disabled
to ignore the required
flag.
Sharing here the fixed Stackblitz with a possible solution and small improvement (removed the ngModel
You have a similar issue raised on this thread form validation on hidden fields
Upvotes: 1