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
My question is how can I import a CSS class to my attribute directive? Do I have to convert my CSS class to JSON?
Original OP was asking how to use Renderer. I've included the @HostBinding for completeness.
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() {
}
}
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');
}
}
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.
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');
}
}