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?
The preferred way to do this in a directive is to use the @HostBinding decorator. I think this is only useful to completely replace the classes that may already be defined in the HTML. How would I add a class with this method? Renderer seems more flexible.
As with components, you can add multiple directive property bindings to a host element.
If you're looking for a quick and clean way to add one or more static classes to the host element of your component (i.e., for theme-styling purposes) you can just do: @Component({ selector: 'my-component', template: 'app-element', host: {'class': 'someClass1'} }) export class App implements OnInit { ... }
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'); } }
Why would you want to use the Renderer or Renderer2 class? The preferred way to do this in a directive is to use the @HostBinding decorator.
Example:
import { HostBinding } from '@angular/core'; @Directive({ selector: '[myDirective]' }) export class MyDirective { @HostBinding('class') className = 'my-directive-css-class'; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With