2
votes

I have a bootstrap3-based template and I am adding angular2 to it.

I need to change the body's classes , which is my root component selector,when changing the route from the SignIn to the rest of the application.

Root Component

@Component({
    selector: 'body',
    directives: [ROUTER_DIRECTIVES],
    templateUrl: '<router-outlet></router-outlet>'
})
export class AppComponent {

    loggedIn = true;

    @HostBinding('class.class1')
    @HostBinding('class.home-page') homeBodyClasses = false;

    @HostBinding('class.class3')
    @HostBinding('class.login-page') loginBodyClasses = false;

    constructor(private router: Router) { }

    ngOnInit() {
        if (!this.loggedIn) {
            this.router.navigate(['SignIn']);
        } else {
            this.router.navigate(['Home']);
        }
          this.router.events.subscribe(event => {
            console.log(event);
            if (event instanceof NavigationEnd) {
                if (event.urlAfterRedirects === '/SignIn') {
                    this.homeBodyClasses = false;
                    this.loginBodyClasses = true;
                }else{
                      this.homeBodyClasses = true;
                    this.loginBodyClasses = false;
                }
            }
        });
    }
    
    

I subscribed to the router navigation events but nothing happens when the url is changed although the values for the @HostBinding are changed.

I tried emitting events from the children components to the body and change the body tag to catch the event like this but nothing happened.

<body (eventName) = "changeBodyClass($event)"></body>

What am I doing wrong ? I don't understand when should I change the values of @HostBinding so that it takes effect. I am using angular2.0.0-rc.5

1
I solved it by using jquery instead to add classes to the body in the function ngOnInit() and remove them in ngOnDestroy().Yassmeen Mahmoud

1 Answers

0
votes

You cannot use @HostBinding outside app-root component.

You can use body as the selector for the app root component and then use @HostBinding or you can use Renderer2 to modify the body class. Using jquery to do this is not advisable.

With Renderer2 you can do something like

renderer.addClass(document.body, "myClass"); 

or

renderer.removeClass(document.body, "myClass");