Reputation: 1640
I have a very long form, but I'd like to disable a specific button (on the template, I don't wanna do it on the component) only if a specific field is empty or has some validation errors, this is a sample of my form:
<form #myForm="ngForm">
<div class="form-group">
<label>Email</label>
<input [(ngModel)]="email" #email="ngModel" name="my_email" type="text" class="form-control" required>
<span *ngIf="email.errors?.required">
This field is required
</span>
</div>
<button [disabled]="myForm.email.errors?.required">Some action</button>
</form>
I don't need to have a full valid form to disable that button, I just wanna check based on the value of that specific input.
How can I do it? what am I missing?
Upvotes: 0
Views: 3275
Reputation: 2503
1 - Rename the template variable #email to #emailInput or any name different from 'email' which is the name of a model property..
<input [(ngModel)]="email" #emailInput="ngModel" name="my_email" type="text" class="form-control" required>
2 - Use the template variable #emailInpunt in the disabled property of the button and in the span which shows the erros.
<button [disabled]="emailInput.errors?.required">Some action</button>
<span *ngIf="emailInput.errors?.required">
This field is required
</span>
The full code:
<form #myForm="ngForm">
<div class="form-group">
<label>Email</label>
<input [(ngModel)]="email" #emailInput="ngModel" name="my_email" type="text" class="form-control" required>
<span *ngIf="emailInput.errors?.required">
This field is required
</span>
<button [disabled]="emailInput.errors?.required">Some action</button>
</div>
</form>
Try it on the Stackblitz
Upvotes: 0