Angular 2 keyup.enter for div tag

13,630

Solution 1

try this code. does this help. html

<div class="data_card" *ngIf="!Add.showEdit" (keydown)="handleKeyboardEvent($event)">

// component

@HostListener('document:keydown', ['$event'])
    handleKeyboardEvent(event: KeyboardEvent): void {
        if (event.keyCode === 13) {
            **// do your code here**
        }
    }

Solution 2

check out this answer. How to bind keyboard events to div elements?.

use tabindex: The tabindex global attribute is an integer indicating if the element can take input focus (is focusable)

Share:
13,630

Related videos on Youtube

Sarath
Author by

Sarath

Updated on June 30, 2022

Comments

  • Sarath
    Sarath almost 2 years

    I need to trigger one function from selected div enter key is pressed. I wrote the following code but it's not working.

    <div class="data_card" *ngIf="!Add.showEdit" (keyup.enter)="myfunction($event)">
    <!-- Some content -- >
    </div>
    
    
    myfunction($event){
          $event.preventDefault();
          alert("sadsa");
    }
    

    How to trigger this function from div enter key is pressed?

  • Sarath
    Sarath almost 7 years
    My app developing using angular 2. Is it possible to do with angular 2 stuffs?
  • Sarath
    Sarath almost 7 years
    (keydown)="handleKeyboardEvent($event,index)" i need to pass some other parameter from html . But when i pass value like this i am getting undefined. How can i pass other parameter?
  • Shailesh Ladumor
    Shailesh Ladumor almost 7 years
    what you want to pass? input value?
  • Sarath
    Sarath almost 7 years
    No there i am using ngfor i need to pass selected div index value
  • Avram Virgil
    Avram Virgil almost 7 years
    in your ngFor just add the i = index and on all your div elements inside event just add the i, you should recieve the event and the index for that div (keydown)="handleKeyboardEvent($event, i)"
  • Shardul
    Shardul almost 6 years
    when do we remove the handler?
  • MrHIDEn
    MrHIDEn almost 4 years
    This answer uses JQuery, not Angular 2+.
  • nipun-kavishka
    nipun-kavishka over 3 years
    this solution is great and can use for many things, also using "event.key" you can get the key name that pressed!