简体   繁体   中英

Angular - How to trigger keyboard events on button click?

I have provided two separates button for Ctrl+z and Ctrl+y. I want the Ctrl+z and Ctrl+y functionality to be performed on the click of a button. Here is my function.

undoText(event:MouseEvent){
    var element =   document.getElementById("undoBt")
     if(element){
        element.dispatchEvent(new KeyboardEvent('keydown',{composed: true, bubbles:true, cancelable:true, code:"ControlLeft", ctrlKey:true, key:'Control',keyCode:17, location:1}));
        element.dispatchEvent(new KeyboardEvent('keydown',{bubbles:true,   cancelable:true, code:"KeyZ", composed:true, ctrlKey:true, key:'z', keyCode: 90}));
       }

  }

Here is my html.

<mat-icon matTooltip="Undo"  (click)="undoText($event)" *ngIf="svgInit" id="btn1" class="undo" svgIcon="undo" aria-hidden="false" aria-label="undo">
        </mat-icon>

To achieve this, I am trying to trigger Ctrl+z and Ctrl+y on button click but they are not getting triggered and I'm not able to set isTrusted property true.

What is wrong with the code?

(keyup.enter)="keyUpFunction($event)"

Where keyUpFunction($event) is your function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM