How to Give Class to a Host Element in Angular 2 with @Hostbinding

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



Leave a reply



Submit