How to add "class" to host element?
You can simply add @HostBinding('class') class = 'someClass';
inside your @Component class.
Example:
@Component({
selector: 'body',
template: 'app-element'
})
export class App implements OnInit {
@HostBinding('class') class = 'someClass';
constructor() {}
ngOnInit() {}
}
Günter's answer is great (question is asking for dynamic class attribute) but I thought I would add just for completeness...
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 {
...
}
And if you use a class on the entry tag, Angular will merge the classes, i.e.,
<my-component class="someClass2">
I have both someClass1 & someClass2 applied to me
</my-component>
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
}
Stackblitz demo at https://stackblitz.com/edit/angular-dynamic-hostbinding
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;
}