Search code examples
angularkeyup

Duplicated call to function in Angular4 button


So,I have an angular input area like this:

<div class="form-group row">
        <div class="col-md-10">
            <pre class="card card-block card-header">Search Publication by id: {{id}}</pre>
            <input type="text"
                   class="form-control"
                   ngui-auto-complete
                   [(ngModel)]="id"
                   [source]="publications"
                   value-formatter="id, title"
                   list-formatter="id, title"
                   />
            <button class="btn btn-primary" (keyup.enter)="search(id.id)" (click)="search(id.id)">Search Publication</button>
         </div>
    </div>

The idea is to give the user the option to make the call to the search function via keyboard or mouse.

The problem I find is that the call is duplicated, it calls it once for the keyup.enter and again for the click

Is there any easy way to avoid this that doesn't imply customized directives?


Solution

  • In a form Enter causes the button to trigger the click event anyway, therefore just adding the click handler should do

    <button class="btn btn-primary" (click)="search(id.id)">Search Publication</button>