原始 OP 询问如何使用渲染器。为了完整性,我已经包含了@HostBinding。
使用@HostBinding
要为元素添加类,您可以使用@HostBinding
import { Directive, HostBinding} from '@angular/core';
@Directive({
selector: '[myDirective]',
})
export class MyDirective {
@HostBinding('class')
elementClass = 'custom-theme';
constructor() {
}
}
将@HostBinding 与多个类一起使用
为了让多个类使用起来更舒服,您可以使用 ES6 getter 并将这些类连接在一起,然后再返回它们:
import { Directive, HostBinding} from '@angular/core';
@Directive({
selector: '[myDirective]',
})
export class MyDirective {
protected _elementClass: string[] = [];
@Input('class')
@HostBinding('class')
get elementClass(): string {
return this._elementClass.join(' ');
}
set(val: string) {
this._elementClass = val.split(' ');
}
constructor() {
this._elementClass.push('custom-theme');
this._elementClass.push('another-class');
}
}
使用渲染器
更底层的 API 是 Renderer2。 Renderer2 在您想要应用到元素的动态类集时很有用。
示例:
import { Directive, ElementRef, Renderer2 } from '@angular/core';
@Directive({
selector: '[myDirective]',
})
export class MyDirective {
constructor(private renderer: Renderer2, hostElement: ElementRef) {
renderer.addClass(hostElement.nativeElement, 'custom-theme');
}
}