Search code examples
htmlangularvalidationrequiredangular-validation

Validation `Required` is not working with radiobtn when using ngFor in Reactive forms


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


Solution

  • input[radio] needs to have both [name] and [attr.name] to be set.