这些装饰器允许一个指令或组件操纵其宿主元素并响应它——指令所在的元素(或组件自己的根元素)。@HostBinding 在宿主元素上设置属性/特性;@HostListener 监听其事件。
@HostBinding — 绑定到宿主属性/特性
ts
{ , } ;
({ : })
{
() isActive = ;
() color = ;
() role = ;
}
@HostBinding 反应式地将宿主元素上的 class/style/attribute/property 绑定到组件字段——改变字段,宿主就会更新。
import { Directive, HostListener, HostBinding } from "@angular/core";
@Directive({ selector: "[appHighlight]" })
export class HighlightDirective {
@HostBinding("style.background") bg = "";
@HostListener("mouseenter") onEnter() {
this.bg = "yellow"; // changing the field updates the host via HostBinding
}
@HostListener("mouseleave") onLeave() {
this.bg = "";
}
@HostListener("click", ["$event"]) onClick(event: MouseEvent) {
console.log("host clicked", event);
}
}
@HostListener 订阅宿主上的 DOM 事件(可以接收 $event 和其他参数)。它们共同让指令完全自包含:监听其宿主上的事件并反应式地更新宿主的外观。
<p appHighlight>Hover me</p>
→ mouseenter fires onEnter() → sets bg='yellow' → @HostBinding updates the <p>'s background
→ mouseleave fires onLeave() → clears it
@Directive({
selector: "[appHighlight]",
host: { // equivalent, declared in metadata
"[class.active]": "isActive",
"(click)": "onClick($event)",
},
})
@HostBinding 和 @HostListener 是指令与其宿主元素交互的标准工具——以声明方式添加类/样式/特性并响应事件,无需手动获取 ElementRef.nativeElement 并连接监听器。
它们对于清晰地构建可复用的行为指令(高亮、提示、可拖拽、无障碍小部件)至关重要,并且它们自动处理变更检测和监听器清理,这些是手动 DOM 代码必须管理的。