I am trying to do a check if a text input is empty or not in angular 4. I am not using forms for this. It's just an input field. When I execute the addLocaton function in the button below the check needs to happen.
my input field
<ion-input type="text" placeholder="Enter a Town, Province or City" name="newPlace" [(ngModel)]="newPlace" id="empty"></ion-input>
<button ion-button block type="submit" (click)="addLocation()">ADD AND SAVE MORE LOCATIONS</button>
ts file
addLocation(){
if( document.getElementById('empty').value === '' ){
alert('empty');
}
}
The proper way
change
type="button"
instead oftype="submit"
as the suggestion from @edkevekedBut you could do this way for passing the model object via method instead of using plain JavaScript code
or use the two way binding
(click)="addLocation()"
and ts could be
What you are doing is all right. Just a small correction would do the thing for you. If you use type as
submit
then the entire form gets submitted. Normally this ships with Angular 4/5 reactive forms. if you set the type as abutton
you will be able to fire the method which is declared in the click event.corrected code:-
Use
type="button"
instead oftype="submit"
Since you're not using form, to handle your click action, here is the way to go.