How to add "class" to host element?

lascarayf picture lascarayf · Jan 6, 2016 · Viewed 150.1k times · Source

I dont't know how to add to my component <component></component> a dynamic class attribute but inside the template html (component.html).

The only solution I found is to modify the item via "ElementRef" native element. That solution seems a little complicated to do something that should be very simple.

Another problem is that CSS has to be defined outside component scope, breaking component encapsulation.

Is there a simpler solution? Something like <root [class]="..."> .... </ root> inside the template.

Answer

G&#252;nter Z&#246;chbauer picture Günter Zöchbauer · Jan 6, 2016

This way you don't need to add the CSS outside of the component:

@Component({
   selector: 'body',
   template: 'app-element',
   // prefer decorators (see below)
   // host:     {'[class.someClass]':'someField'}
})
export class App implements OnInit {
  constructor(private cdRef:ChangeDetectorRef) {}
  
  someField: boolean = false;
  // alternatively also the host parameter in the @Component()` decorator can be used
  @HostBinding('class.someClass') someField: boolean = false;

  ngOnInit() {
    this.someField = true; // set class `someClass` on `<body>`
    //this.cdRef.detectChanges(); 
  }
}

Plunker example

This CSS is defined inside the component and the selector is only applied if the class someClass is set on the host element (from outside):

:host(.someClass) {
  background-color: red;
}