Validation in angular 2
I am making a litte todo app with angular.
in my component.html I want to check. If you don't enter anything in the text box, then the text is displayed with the caption "title". And when there is less than 5 characters in the text box, the text is also displayed.
But it doesn't work.
When I launch my app, I only see my textbox without my todo. When I enter 1 letter in the textbox, I see my todos. Also when I only have 4 characters, I don't see a notification that says I should have 5 characters.
This is my code:
<h3>Add todo</h3>
<form >
<input class="form-control" type="text" id="text" required minlength="5" [(ngModel)]="text" name="text" >
<div *ngIf="text.errors && (text.dirty || text.touched)" class="alert alert-danger">
<div [hidden]="!text.errors.required">
Title is required
</div>
<div [hidden]="!text.errors.minlength">
titel moet minstens 5 karakters zijn
</div>
</div>
</form>
<button class="btn btn-danger" (click)="addTodo()">test</button>
source to share
To bind error messages, you need to reference the template with ngModel
. For example: #text="ngModel"
.
Two-way binding won't work with the same name, so they must be different. Here I actually changed the name of the two-way binding variable to theText
:
<input type="text" id="text" required minlength="5" [(ngModel)]="theText"
name="text" #text="ngModel">
Here's the complete template, note that we are giving the form a template link #myForm="ngForm"
and on submit we are passing the values ββfrom that form:
<form #myForm="ngForm" (ngSubmit)="submitForm(myForm.value)">
<input type="text" id="text" required minlength="5" [(ngModel)]="theText" name="text" #text="ngModel" >
<div *ngIf="text.errors && (text.touched || text.dirty)" class="alert alert-danger">
<div [hidden]="!text.errors?.required">
Title is required
</div>
<div [hidden]="!text.errors?.minlength">
titel moet minstens 5 karakters zijn
</div>
</div>
</form>
As an alert, you might not even need two-way binding (??) here? You can retrieve data from an object that you get from form ( myForm.value
) values .
source to share