angularhtmlangular-templatecustom-attribute

Angular rendered DOM html custom attributes


I am new to frontend and i began using Angular.

When I look to the final DOM i see code like this

<style>
.pane[_ngcontent-c0]~
....
}
</style>

<div _ngcontent-c0 class="pane" ...

This is using CSS attribute selectors but my question is related with the custom attribute "_ngcontent-c0", in html5 there is a new feature with the name of "data custom attributes that are prefixed with (data-*) name. In this case the custom attribute is not using the data- syntax , this does not make the document invalid ?Is it possible to define custom attributes without the data- prefix ?

Thanks in advance Best regards


Solution

  • You are correct that this is not valid HTML anymore because _ngcontent-c0 is not specified in the HTML spec. But this just means that the attribute is not defined.

    You can always add custom attributes but these will most likely not have effects because the browser just ignores them. Be aware that this might change in the future.

    What these custom attributes are used for is the encapsulation of CSS styles. In CSS you can still use these custom attributes for style definitions and the styles of one component will not bleed into the styles of another component. This is basically a workaround for the Shadow DOM. Angular automatically adds these custom attributes to all styles of a component to encapsulate its styles.