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

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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'] })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.