原来的OP是问如何使用Renderer。为了完整起见,我添加了 @HostBinding。
使用@HostBinding
要将类添加到元素,您可以使用@HostBinding https://angular.io/api/core/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是渲染器2 https://angular.io/docs/ts/latest/api/core/index/Renderer2-class.html。当您想要将一组动态类应用于元素时,Renderer2 非常有用。
Example:
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');
}
}