0

I need to add a class attribute dinamically the a host component made with Angular 2.

What I want to do isn't this way: How to add "class" to host element?

In the case above it would be necessary the hardcoding of the class. My objective is to add a unknown class, at compile time, received as a string by parameter or something like.

I need to inject the class from inside Angular 2, not define it as an attribute. It also should not avoid to pass another classes by parameter. I also would like to avoid handle the native dom.

Community
  • 1
  • 1
Natanael
  • 1,900
  • 5
  • 21
  • 34

1 Answers1

3

Use Renderer:

// Renderer.setElementClass(renderElement: any, className: string, isAdd: boolean) : any

class MyComponent {
  constructor(private elRef:ElementRef, private renderer: Renderer) {}

  ngOnInit() {
    this.renderer.setElementClass(this.elRef.nativeElement, "whatever", true || false)
  }
}
Sasxa
  • 36,894
  • 14
  • 85
  • 98