Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting attr.required to "CONDITION" does not check anything

I'm creating a form, where a input field should/ shouldn't be required based on a previous condition (e.g. a checkbox).

If the required attribute is set an the element, the required validation works just fine. If I set the required attribute with [attr.required]="CONDITION", it doesn't check it at all.

Here is a plnkr sample: https://plnkr.co/edit/vPfmgvLxUjNyNXHtkY24 (based on on the hero example from the documentation).

Code (relevent part):

  <form #heroForm="ngForm">  
      <div class="form-group">
        <label for="name">Required label Test</label>
        <input type="checkbox" class="form-control" [(ngModel)]="cbReqired" name="cbReqired" id="cbReqired">
      </div>

      <div [hidden]="!cbReqired">Now the Textbox should be required! (<code>required="true"</code> is set!)</div>

      <div class="form-group">
        <label for="name">Name</label>
        <input id="name" name="name" class="form-control" [attr.required]="cbReqired" [(ngModel)]="hero" #name="ngModel">

        <div *ngIf="name.invalid && (name.dirty || name.touched)" class="alert alert-danger">

          <div *ngIf="name.errors.required">
            Name is required.
          </div>
        </div>
      </div>

      <button type="submit" class="btn btn-default" [disabled]="heroForm.invalid">Submit</button>
      <button type="button" class="btn btn-default" (click)="heroForm.resetForm({})">Reset</button>
  </form>
like image 817
Stefan Avatar asked Oct 02 '17 16:10

Stefan


1 Answers

You just need to use [required] instead of [attr.required]. Here is the working plunker: https://plnkr.co/edit/B6dM2BvD3hMH3Skv6uy5?p=preview

like image 195
Commercial Suicide Avatar answered Oct 13 '22 07:10

Commercial Suicide