Using Angular component name in Less stylesheet don't match generated DOM

Viewed 580

I'm leaning Angular by following Udemy course and I have this style:

server dl {
    display: flex;
}

and server component and it don't work. The style is not applied to html. Because generated style look like this:

server[_ngcontent-c1]   dl[_ngcontent-c1] {
  display: flex;
}

and DOM look like this:

<server _ngcontent-c0="" _nghost-c1="">
   <dl _ngcontent-c1="">
     <dt _ngcontent-c1="">Plantform</dt>
     <dd _ngcontent-c1="">Linux x86_64</dd>
   </dl>
</server>

_ngcontent-c0 instead of _ngcontent-c1, why this is happening? Why the style don't match the DOM?

I'm using Angular app using generated by CLI with Less (but I've created component by hand using server as selector, the same happen if name is app-server).

Why this attribute selectors are added? What about if I use this component in different place? I want to match all elements inside component that's why I've added server as selector to always match all inside this component.

How can I use component name that is added to html as root for my whole style? Or is this not good practice in Angular and this is handled other way, if so can someone explain?

2 Answers

Every element of a component is scoped-automagically / polyfilled by angular (in accordance with css spec for scoping) using those attributes you noticed. So basically, you don't have to write component-name element when you write css for that component but you can just write:

dl {
    display: flex
}

Angular will make sure that this style is only applied to dl inside server by using the generated attributes, it is essentially a polyfill for css scoping. If all your targeted browsers support css scoping natively, you can even set ViewEnacpsulation.Native

In some cases where you decide to style the root element, you have to use the special selector :host

The :host selector is the only way to target the host element. You can't reach the host element from inside the component with other selectors because it's not part of the component's own template. The host element is in a parent component's template.

So instead of writing server {background: red} you will write :host {background: red}

This is also inline with css spec for scoping.

Read more about CSS coping and component based CSS to know more about this strategy.

As a primer read the base documentation in Angular

Also, note that you can add your css to any global stylesheet like the way you did:

server dl {
    display: flex
}

Which way to go largely depends on how you plan to manage and scale css.

You can use at .TS file below the class.
This is delete all this _ngcontent

 @Component
   selector,
   template,
   styles,

This code encapsulation: ViewEncapsulation.None

Related