Issue
I have two Inputs, that have to be required, in order to use the "Add"-Button or I was thinking to use *ngIf to make the button visible or not, but it doesnt work. Whats wrong?
<input
#neueEintragBeschreibung
placeholder="Eintrag hinzufügen"
class="lg-text-input"
/>
<input
#neuesEintragFaelligkeitsdatum
placeholder="Faelligkeitsdatum hinzufügen"
class="lg-text-input"
/>
<div *ngIf="neueEintragBeschreibung.value">
<button class="btn-primary" (click)="addEintrag(neueEintragBeschreibung.value, neuesEintragFaelligkeitsdatum.value)">
Add</button>
</div>
Solution
You're not supposed to access input.value this way. You should use the forms API to do so. E.g:
<form #form="ngForm" (ngSubmit)="handleSubmit(form)">
<input type="text" required name="myField" ngModel />
<ng-container *ngIf="form.valid">
<button type="submit">Add</button>
</ng-container>
</form>
handleSubmit(form: NgForm) {
console.log(`You entered: ${form.value.myField}`);
}
What's happening here:
- You create a form with one field, called "myField".
- You make "myField" required by using the
requiredattribute. - You render the "Add" button only when the form is valid. Since the form has a required field, it will only be valid once this field is filled by the user.
Remember to add FormsModule to your module's imports.
Answered By - Allan Juan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.