user1203497
user1203497

Reputation: 517

Angular 2+ : Component style keeps affecting other components

Got home component with background-color:red written into its scss and then got user component with background-color:green written into its scss. I start my app, I am at home, got red background, go to user page, got green background. Works like it should...but now when I go back my home component background is still green. All components have ViewEncapsulation.None. If I start navigation from user page, same things happen, but background colors vica-vera.

I always understood that point of component style is to affect only its component and not others. Is it not how that supposed to work?

Edit: If I set ViewEncapsulation.Emulated I see no styling from component style scss file being applied, so both pages are having white background. This is how my home component file looks:

import { Component, OnInit, ViewEncapsulation } from '@angular/core';


@Component({
    selector: 'app-home',
    templateUrl: './home.component.html',
    styleUrls: ['./home.component.scss'],
    encapsulation: ViewEncapsulation.Emulated,
})

export class HomeComponent implements OnInit {

    ngOnInit() {

    }

}

Edit: You see my problem was that I was setting background color for <body>, but the body aint part of the template, this why encapsulation: ViewEncapsulation.Emulated and component stylesheets aint affecting it.

Upvotes: 4

Views: 4433

Answers (2)

Tushar Walzade
Tushar Walzade

Reputation: 3809

You need to encapsulate your view to Emulated, so that your component decorator will look like the following -

@Component({
    // ...
    encapsulation: ViewEncapsulation.Emulated,
})

It will scope your styles to the specific component only.

Here's more reference about View Encapsulation

Upvotes: 3

John Velasquez
John Velasquez

Reputation: 3451

The reason it never changes back to the expected color.

Because the first component loads its css in to the dom and stays their forever until the window is not closed. And the reason why the second time of route change is correct because it will override your same class, ids or tag styles that are existing once the second component is rendered.

So my suggestion is, make the use of router events and detect each paths you want to change colors and change the body element class.

example:

export class AppComponent {
  name = 'Angular';

  constructor(private router: Router) {
    this.router.events.subscribe((event) => {
      if (event instanceof NavigationEnd) {
        console.log(event.url)
        if (event.url == '/') {
          document.body.className = 'home';
        } else if (event.url == '/test') {
          document.body.className = 'test';
        } else if (event.url == '/hello') {
          document.body.className = 'hello';
        }
      }
    });
  }
}

see stackblitz below for the complete guide:

https://stackblitz.com/edit/angular-svktf1

Upvotes: 0

Related Questions