Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Angular Component CSS encapsulation work?

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

like image 263
TAHA SULTAN TEMURI Avatar asked Sep 12 '19 11:09

TAHA SULTAN TEMURI


Video Answer


1 Answers

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

like image 64
Gustavo Lopes Avatar answered Sep 22 '22 13:09

Gustavo Lopes