Noura Ali
Noura Ali

Reputation: 73

pressing enter calls the code in click method

I have two input fields and button. when I press Enter in one of the two input fields supposed to execute some code but what happens the code of button is executed

<div class="input-group">
        <button mat-raised-button color="primary" 
     (click)="getCurrency()"
          style="margin-right: 10px;width: 20px">...</button>
        <div class="input-group-prepend">
          <input id="currencyDesc"  type="text" size="15" [(ngModel)]='name' [ngModelOptions]="{standalone: true}">
        </div>
        <div class="input-group-prepend">
          <input formControlName="CRCYIsn" type="text" size="4" (keyup.enter)="currencyByIsn()">
        </div>

        <label> : العملة</label>
      </div>

Upvotes: 2

Views: 94

Answers (4)

Shashank Vivek
Shashank Vivek

Reputation: 17494

Try (keydown.enter)="$event.preventDefault()" as below on that button:

<button mat-raised-button color="primary" 
       type="button"
       (keydown.enter)="$event.preventDefault()" 
       (click)="getCurrency()"
        style="margin-right: 10px;width: 20px">...</button>

If it's a form, try to put this code on the <form> tag itself

Upvotes: 3

AVJT82
AVJT82

Reputation: 73337

Buttons inside forms are by default of type submit. Tell the button to be of type button and it shouldn't be fired:

<button mat-raised-button type="button" color="primary" (click)="getCurrency()">

DEMO

Also like mentioned, don't mix reactive forms with ngModel.

Upvotes: 0

Cafeteru_
Cafeteru_

Reputation: 71

I will change the next things:

  • First, you should use only formcontrolname if that div inside a form. It´s better than use ngForm.
  • Second, I think it´s better use (click) instead of (keyup.enter), or directly use (ng-submit) if this method is executed when the form is submitted.
  • Finally, don't mix html code with css, use css files for that component that is one of Angular's best qualities

Upvotes: 0

Sameer
Sameer

Reputation: 519

For ENTER key, why not use (keyup.enter)

  <div class="input-group">
            <button mat-raised-button color="primary" 
         (click)="getCurrency()"
              style="margin-right: 10px;width: 20px">...</button>
            <div class="input-group-prepend">
              <input id="currencyDesc" (keyup.enter)="doSomething()" type="text" size="15" [(ngModel)]='name' [ngModelOptions]="{standalone: true}">
            </div>
            <div class="input-group-prepend">
              <input formControlName="CRCYIsn" (keyup.enter)="doSomething()" type="text" size="4" (keyup.enter)="currencyByIsn()">
            </div>

            <label> : العملة</label>
          </div>

Upvotes: 0

Related Questions