使用指令将类添加到宿主元素 [英] Using a directive to add class to host element
问题描述
我目前正在学习 Angular 2.我了解如何使用 Angular Renderer
来设置 ElementStyle
,但现在我想使用 Renderer
方法:
I am currently learning Angular 2. I understood how to use the Angular Renderer
to set an ElementStyle
, but now I would like to use the Renderer
method:
setElementClass(renderElement: any, className: string, isAdd: boolean) : void
我的问题是如何将 CSS 类导入到我的属性指令中?我是否必须将我的 CSS 类转换为 JSON?
My question is how can I import a CSS class to my attribute directive? Do I have to convert my CSS class to JSON?
推荐答案
原 OP 是问如何使用 Renderer.为了完整性,我已经包含了@HostBinding.
Original OP was asking how to use Renderer. I've included the @HostBinding for completeness.
要将类添加到元素,您可以使用 @HostBinding
To add a class to an element you can use @HostBinding
import { Directive, HostBinding} from '@angular/core';
@Directive({
selector: '[myDirective]',
})
export class MyDirective {
@HostBinding('class')
elementClass = 'custom-theme';
constructor() {
}
}
在多个类中使用@HostBinding
为了让多个类更易于使用,您可以使用 ES6 getter 并在返回它们之前将类连接在一起:
Using @HostBinding with multiple classes
To make multiple classes more comfortable to use, you can use the ES6 getter and join the classes together before returning them:
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 很有用.
Using Renderer
The more low level API is Renderer2. Renderer2 is useful when you have a dynamic set of classes you would like to apply to an element.
示例:
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');
}
}
这篇关于使用指令将类添加到宿主元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!