angular 4 click button function is not fired

拥有回忆 提交于 2020-01-05 08:56:06

问题


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');
     }
  }

回答1:


The 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');
         }
      }



回答2:


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 type submit 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>


来源:https://stackoverflow.com/questions/49934280/angular-4-click-button-function-is-not-fired

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!