Natanael
Natanael

Reputation: 2420

How to add classes to host in angular 2?

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.

Upvotes: 0

Views: 3373

Answers (1)

Sasxa
Sasxa

Reputation: 41274

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)
  }
}

Upvotes: 3

Related Questions