Add Class to a Host Element using @hostbinding in Angular 2

@HostBinding is decorator in Angular.
@HostBinding lets you set properties on the host element or component.HostBinding will bind property to host element,if binding is change then HostBinding will update the host element.

I was recently faced a situation that if user is login with Admin Role then I need to add some class on my app-root (host element).so I used @HostBinding.

For using @HostBinding we need to imort HostBinding in our component.


import { HostBinding } from '@angular/core';

and I add following code on my component.


@HostBinding('class.new-class') chkAdmin: boolean = false;

By default <app-root> element not have any class, When user is login with Admin role then I just set chkAdmin true in my login function.
now <app-root> element have class and its look <app-root class=”new-class”>.

Full code example:-

import { Component, OnInit, HostBinding } from '@angular/core';
import { AuthService } from './auth.service';

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html'
})

export class AppComponent implements OnInit{
loginData: any = {
email: "example@mail.com",
password: "test"
}
constructor(private authService: AuthService) {}
ngOnInit() {}
private login(): void {
 this.authService.login(this.loginData).subscribe((data : boolean) =>{
 this.chkAdmin = data;
 }, (err: any) => console.log(err));
}
@HostBinding('class.new-class') chkAdmin: boolean = false; 
}

Leave a Reply

Your email address will not be published. Required fields are marked *