There are different ways to solve that, depending of the situation or what we want to achieve.
Solution A : (Static class)
@Component({
selector: 'app-component',
template: '<ng-content></ng-content>',
})
export class App implements OnInit {
constructor(private cdRef:ChangeDetectorRef) {}
someField: boolean = false;
@HostBinding('class.someClass') someField: boolean = false;
ngOnInit() {
this.someField = true; // set class `someClass` on `<app-component>`
//this.cdRef.detectChanges();
}
}
Solution B : (dynamic class)
If you want to add a dynamic class to your host element, you may combine your HostBinding
with a getter as
@HostBinding('class') get class() {
return aComponentVariable // the name of the class.
}
Example:
HTML: app.component.html
<h3>Pick the color of the text component</h3>
<input type="radio" name="headingColor" [value]="'Blue'" id="Blue" [(ngModel)]="headingColor"><label for="Blue">Blue</label>
<input type="radio" name="headingColor" [value]="'Red'" id="Red" [(ngModel)]="headingColor"><label for="Red">Red</label>
<input type="radio" name="headingColor" [value]="'Green'" id="Green" [(ngModel)]="headingColor"><label for="Green">Green</label>
TYPESCRIPT: app.component.ts
import { Component, HostBinding } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
headingColor: string = 'Black';
@HostBinding('class') get HeadingClass() {
return this.headingColor
}
}
STYLESHEET: app.component.css
:host.Black{
color: Black;
}
:host.Green {color: Green}
:host.Blue {color: Blue}
:host.Red {color: Red}
Solution C : (Use of ElementRef property)
import {Component, OnInit, ElementRef} from '@angular/core';
@Component({
selector: 'my-app',
template: '<ng-content></ng-content>'
})
export class AppComponent implements OnInit {
private currentIconClass: string;
get hostElement(): HTMLElement {
return this._elementRef.nativeElement;
}
constructor(public _elementRef: ElementRef<HTMLElement>) {
}
ngOnInit() {
this.setIconClass(this.hostElement.textContent);
}
private setIconClass(iconClass: string): void {
if (!iconClass) {
console.warn('Missing iconClass!');
return;
}
this.clearElement();
if (this.currentIconClass) {
this.hostElement.classList.remove(this.currentIconClass);
}
this.currentIconClass = iconClass;
this.hostElement.classList.add(this.currentIconClass);
}
private clearElement(): void {
this.hostElement.textContent = undefined;
}
}