admin管理员组文章数量:1314471
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');
}
}
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');
}
}
Share
Improve this question
edited Apr 20, 2018 at 5:05
edkeveked
18.4k10 gold badges59 silver badges95 bronze badges
asked Apr 20, 2018 at 4:58
RRBRRB
2,1169 gold badges48 silver badges84 bronze badges
1
-
2
Its unnecessary to make
document.getElementById
you can simply go for the model newPlace and check if its either '' or 'Enter a Town, Province or City' – Doomenik Commented Apr 20, 2018 at 5:00
2 Answers
Reset to default 4The proper way
change type="button"
instead of type="submit"
as the suggestion from @edkeveked
<button ion-button block type="button" (click)="addLocation(newPlace)">ADD AND SAVE MORE LOCATIONS</button>
But you could do this way for passing the model object via method instead of using plain JavaScript code
addLocation(newPlace){
if(newPlace === '' || newPlace === undefined ){
alert('invalid');
}
}
or use the two way binding
(click)="addLocation()"
and ts could be
addLocation(){
if(this.newPlace === '' || this.newPlace === undefined ){
alert('invalid');
}
}
Use type="button"
instead of type="submit"
With the type
button
the button has no default behavior. It can have client-side scripts associated with the element's events, which are triggered when the events occur whereas with the typesubmit
it tries to make a form submit action. To catch that action in angular, you need to use the event binding to(ngSubmit)
.
Since you're not using form, to handle your click action, here is the way to go.
<button ion-button block type="button" (click)="addLocation()">ADD AND SAVE MORE LOCATIONS</button>
本文标签: javascriptangular 4 click button function is not firedStack Overflow
版权声明:本文标题:javascript - angular 4 click button function is not fired - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741962703a2407374.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论