簡體   English   中英

Angular 使用@HostListener 來監聽特定的按鈕點擊

[英]Angular using @HostListener to listen to specific click of button

我正在使用 Angular 10,我目前正在使用 jquery 通過 id 監聽按鈕單擊。 我知道這不是用 Angular 做到這一點的正確方法,所以我想改變它。

這是當前的代碼:

$('#tbtn1').click((e) => {
  e.preventDefault(); 
  this.myMethod();
});

我可以使用: @HostListener來偵聽另一個組件上的特定按鈕,就像我在上面的示例中所做的那樣嗎?

我怎樣才能做到這一點?

這是代碼並且它有效(ng-version =“10.1.6”):

app.component.html -

<button (click)="onClick($event)">Demo Button</button>

app.component.ts( extends其他組件)-

export class AppComponent extends DemoComponent {
    @HostListener('document:click', ['$event'])
    onClick(event: MouseEvent): void {
        event.preventDefault();
        this.myMethod();
    }
}

demo.component.ts -

myMethod() {
    console.log('myMethod working!!!');
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM