1. 使用 :host 伪类选择器
在组件的 CSS 文件中:
typescript
// component.css
:host {
display: block;
padding: 16px;
border: 2px solid #1976d2;
border-radius: 8px;
background-color: #f5f7fa;
}
:host(.active) {
background-color: #e3f2fd;
border-color: #0d47a1;
}
:host-context(.dark-theme) {
background-color: #424242;
color: white;
}
2. 使用 host 元数据属性
在 @Component 装饰器中:
typescript
@Component({
selector: 'app-example',
template: `<p>示例组件</p>`,
host: {
'class': 'host-element',
'[class.active]': 'isActive',
'[style.backgroundColor]': 'bgColor',
'[attr.role]': '"button"'
}
})
export class ExampleComponent {
isActive = true;
bgColor = '#e3f2fd';
}
3. 使用 @HostBinding 装饰器
在组件类中:
typescript
import { Component, HostBinding, HostListener } from '@angular/core';
@Component({
selector: 'app-host-binding',
template: `<p>点击我查看效果</p>`
})
export class HostBindingComponent {
@HostBinding('class.active') isActive = false;
@HostBinding('style.backgroundColor') bgColor = '#ffffff';
@HostBinding('attr.role') role = 'button';
@HostListener('click') onClick() {
this.isActive = !this.isActive;
this.bgColor = this.isActive ? '#e3f2fd' : '#ffffff';
}
}
4. 使用 @HostListener 监听宿主事件
typescript
@Component({
selector: 'app-event-listener',
template: `<p>悬停或点击我</p>`
})
export class EventListenerComponent {
@HostBinding('class.hovered') isHovered = false;
@HostListener('mouseenter') onMouseEnter() {
this.isHovered = true;
}
@HostListener('mouseleave') onMouseLeave() {
this.isHovered = false;
}
@HostListener('click', ['$event']) onClick(event: Event) {
console.log('宿主元素被点击', event);
}
}
各种方法对比
| 方法 | 适用场景 | 优点 | 缺点 |
|---|---|---|---|
:host 选择器 |
静态样式 | 简单直观,性能好 | 无法动态改变 |
host 元数据 |
简单的动态样式 | 声明式,简洁 | 功能有限 |
@HostBinding |
复杂的动态样式 | 灵活,功能强大 | 需要更多代码 |
@HostListener |
事件处理 | 响应式交互 | 需要事件处理逻辑 |
最佳实践建议
- 优先使用
:host- 对于静态样式 - 简单动态样式用
host元数据 - 对于简单的条件样式 - 复杂逻辑用
@HostBinding- 当需要复杂逻辑时 - 交互功能用
@HostListener- 处理用户交互