I have a dynamic reactive angular form which builds forms and populates questions inside it dynamically according to questions types retrieved from the database. the problem is the required validation (native HTML5 validation ngNativeValidate) is not working when I add it inside a *ngFor loop
in my form builder I have this part
<div class="row" *ngSwitchCase="'radiobtn'">
<legend class="col-form-label col-sm-6 pt-0">{{question.label}}</legend>
<div class="col-sm-6">
<div class="form-check" *ngFor="let opt of question.options; let i = index">
<label class="form-check-label" [attr.for]="question.key+opt.key">
<input class="form-check-input" type="radio" [name]="question.key" [formControlName]="question.key"
[id]="question.key+opt.key" [value]="opt.key" required />
{{opt.value}}
</label>
</div>
</div>
</div>
I have ngNativeValidate
in the form tag and I have new FormControl(question.value || '', Validators.required)
in the FormGroup builder.
This code is supposed to apply required validation check but it’s not working. when I remove the for loop and make it static the validation works. what is the reason here.
Note: my Angular version is 10
2
Answers
input[radio] needs to have both [name] and [attr.name] to be set.
When working with
native validations
always preferTemplate Driven Forms
, because if you go for template driven, the validation you add, will not trigger the native HTML validations.HTML:
TS:
Stackblitz Demo
But here is an example of reactive driven forms, the gotcha you need to know is that.
When you add a validation, the corresponding directive also needs to be present in HTML, that is why we have required attribute.
HTML:
TS:
Stackblitz Demo