5

I want to understand that if I create two style sheets

Style 1

.heading {
  color: green;
}

Style 2

.heading {
  color: blue;
}

Now if these two styles are written in two different views, when rendering them on a layout as a Partial View, then in this case a conflict could occur and one could override the style of the other.

BUT

Using angular(see page 16), how come these two styles in different components render on the same page with encapsulation? How come the CSS is not overriden?

For example

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

@Component({
 selector: 'app-user-item',
 template: '<p class="heading">abc</p>',
 styleUrls: ['./user-item.css']
})
export class UserItemComponent implements OnInit {

  constructor() {}

  ngOnInit() {}

}

user-item.css

.heading{ color :green}

app-user.component.ts

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

@Component({
 selector: 'app-user',
 template: '<p class="heading">abc</p>',
 styleUrls: ['./user.css']
})
export class UserItemComponent implements OnInit {

  constructor() {}

  ngOnInit() {}

}

user.css

.heading{ color :blue}

When rendering this on a page:

<app-user></app-user>
<app-user-item></app-user-item>

This is the result:

Img

Jesse
  • 3,522
  • 6
  • 25
  • 40
TAHA SULTAN TEMURI
  • 4,031
  • 2
  • 40
  • 66

2 Answers2

6

Angular (by default) emulates a shadow DOM.

It dynamically creates some HTML attributes that are only applicable to elements in that component.

For example:

<app-user></app-user>
<app-user-item></app-user-item>

will be transformed to

<app-user _ngcontent-1></app-user>
<app-user-item _ngcontent-2></app-user-item>

And your css will be transformed to:

.heading[_ngcontent-1] { color: blue }
.heading[_ngcontent-2] { color: green }

You can find a more complete explanation here and the documentation here

Gustavo Lopes
  • 3,794
  • 4
  • 17
  • 57
0

Angular comes with CSS encapsulation out of the box. When generating a new project, the default is for the styles.css file at the root of the project to apply globally to the application, and for component styles, such as the styles found in foo.component.css,to only apply to the foo component and nowhere else. But that is not the only way styles can be encapsulated in Angular, let us take a closer look.@Component({ selector: 'app-foo', templateUrl: './foo.component.html', styleUrls: ['./foo.component.css'] })

Sudhanshu Pal
  • 86
  • 1
  • 2
  • 13