Reputation: 37
This is my input type in Angular
<td>
<input class="form-control" id="id_phone" name="mobileno" type="text" [(ngModel)]="mobileno"
name="mobileno" placeholder="Enter MobileNo" />
</td>
Now I am trying to show an alert if this field in empty on click of button something like this:
clickSubmit(event) {
if (this.mobileno.length==0) {
alert('Field is empty')
} else {
console.log('Everything is ok')
}
}
But I am getting as error after hitting of button something like this, any sort of help is appreciated:
PlaceorderComponent.html:293 ERROR TypeError: Cannot read property 'length' of undefined at PlaceorderComponent.push../src/app/placeorder/placeorder.component.ts.PlaceorderComponent.clickSubmit (placeorder.component.ts:56)
Upvotes: 0
Views: 1505
Reputation: 2926
Although there are multiple ways to validate input before submitting (as @Canolyb1 commented, you could look for build in validators).
In your way you should check the property that you have bind with your input: mobileno
You should also check for null
and undefined
values like this example:
if (this.mobileno && this.mobileno.length) {
console.log('Everything is ok');
} else {
alert('Field is empty');
}
Here I did a StackBlitz example.
Upvotes: 1