maxal90 maxal90 - 2 months ago 4
HTML Question

Why is Angular2 adding random generated attributes to html elements after render

I am having hard time understanding why is Angular2 adding these weird attributes to HTML elements after app is loaded (ex. on provided screenshot"_ngcontent-cxi-6"). I provided screenshot from DevTools with example.

Screenshot from DevTools.

That attribute always has fixed prefix "_ngcontent-". The rest is generated randomly but is consistent on every HTML element.

The problem comes when i want to insert HTML that i generate in Component or retrieve from Server with directive [innerHtml]. In that case elements in inserted HTML code do not get Angular's attribute:

<span [innerHtml]="'<span>some text </span>'"></span>

Result of [innerHtml] binding is on picture below:

enter image description here

CSS styling problem

When i want to style these printed elements, with injected css file, nothing happens.
CSS file is inserted with "styleUrls" property of @Component:

templateUrl: 'someHtmlTemplate.html',
styleUrls: ['someCSSfile.css'],

Style that gets injected into HTML is formatted into this:

span[_ngcontent-cxi-6] {
background: pink;
font-size: 20px;

In this case CSS is looking for span with attribute [_ngcontent-cxi-6], thus making it unable to style it.

Possible solution
This CSS code solves things

:host >>> h3 { color: red; }

is compiled after injection into HTML:

[_nghost-krr-4] > > > span {
background: pink;
font-size: 20px;

But it is a crazy workaround solution for something so simple.


In fact, it depends on the encapsulation mode you use on your component for shadow DOM. By default, it's the emulated mode so Angular2 adds things on elements for this.

  • ViewEncapsulation.None - No Shadow DOM at all. Therefore, also no style encapsulation.
  • ViewEncapsulation.Emulated - No Shadow DOM but style encapsulation emulation.
  • ViewEncapsulation.Native - Native Shadow DOM.