1
HostListener與Angular 4中的DOM事件HostListener與Angular 4中的DOM事件
所以這個問題是關於編碼時的最佳實踐。 考慮我有一個我想要模糊事件的組件。這可以通過兩種不同的方式來實現。
使用DOM事件:
view.html
<input (blur)="onBlur($event)"/>
component.ts
@Component({ selector: 'input-component' template: require('path to view.html') }) export class InputComponent(){ public onBlur(event: Event){ /*on blur action*/} }
在這裏,我已經把一個模糊事件的輸入,我有一個我的組件類中的回調函數。
使用HostListener
component.ts
import { HostListener } from '@angular/core'; @Component({ selector: 'input-component' template: require('path to view.html') }) export class InputComponent(){ @HostListener('blur', ['$event']) onBlur(event: Event) { /*on blur action*/} }
在這裏我實現了與HostListener相同。我知道這在指令類中有很多用處,但我已經看到很多 組件與HostListeners的例子。
我的問題在這裏:
- 哪個是更清潔和更好的實現?
- 堅持使用DOM事件還是使用角鉤會更好嗎?
我會在HostListener除非做了指示選擇DOM事件。這更清楚。 – DeborahK
感謝您的評論。我認爲儘量保持實現儘可能接近DOM是有意義的。 – ronakvp