How to give class to a host element in Angular 2 with @hostbinding
The Angular2 style guide says to prefer @HostBinding
, but this doesn't make host: {...}
a bad thing.
You can use
@Component({
selector: 'left-bar',
templateUrl: 'app/left-bar/left-bar.component.html',
styleUrls: ['app/left-bar/left-bar.component.css']
})
export class LeftBarComponent implements OnInit {
@HostBinding('class.left-bar') leftBarClass = true;
// or @HostBinding('class') leftBarClass = 'left-bar';
ngOnInit() {
}
}
Class is not binded to host element using HostBinding
It's binded but style .hostClass
can be only applied to the elements inside app.component.html
template.
You should be using :host.hostClass
selector instead
Forked Stackblitz
How to add class to host element?
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;
}
Apply class conditionally to component host
You can set the host element class conditionally with @HostBinding
:
condition: boolean = true;
@HostBinding("class") private get hostClass(): string {
return this.condition ? "redBorder" : "";
}
or for a specific class name (e.g. redBorder
):
@HostBinding("class.redBorder") private get hasRedBorder(): boolean {
return this.condition;
}
See these two demos: stackblitz 1, stackblitz 2.
Is it possible to add a dynamic class to host in Angular 2?
You can use something like that:
@Directive({
(...)
host: {
'[class.className]' : 'className',
'[class]' : 'classNames'
}
}
export class MyDirective {
className: boolean;
classNames: string;
constructor() {
this.className = true;
this.classNames = 'class1 class2 class3';
}
}
Related Topics
How to Align Reveal.Js Slides to The Top of The Page
Align Text with Bottom as It Comes in During a Chat
How to Use a SASS $Variable Across Multiple Pages Using @Use
Is There Cross Browser Word-Wrap: Overflow-Wrap Solution
Multiple HTML Div's Using Same CSS Style
Using CSS Attribute Selectors to Target The Src of Background-Image
Making a Row of Divs All Be The Same Height Using CSS
CSS - Floating Two Elements Side by Side
Ie8/9 - Maximum Bytes for CSS File
Trying to Build Less (Less CSS) Using a Build Script with Nodejs
What Is The Max Number CSS Rules I Can Specify in Style Sheet Per Browser
How to Make an <A> 100% Height of <Li>
Column Width in Rich:Datatable