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>
You just need to use [required]
instead of [attr.required]
. Here is the working plunker: https://plnkr.co/edit/B6dM2BvD3hMH3Skv6uy5?p=preview
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With