Skip to content Skip to sidebar Skip to footer

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

Solution 1:

What you see there:

_ngcontent-c0 Is Angulars way of creating a scoped DOM. They inject these attributes for different reasons, one of them e.g. for component-scoped styles.

.pane[_ngcontent-c0] <-- This is a CSS selector. Each CSS rule in the comonents style sheet is scoped to it. It happens in preprocessing.

There is very little human-readable docs on this, this is the best I could find:

https://medium.com/claritydesignsystem/ng-content-the-hidden-docs-96a29d70d11b

You should have no influence on these but the CLI also should not cut anything silently.

Rather the CLI would probably stop compiling due to template syntax error.

By creating a component you create custom HTML tags (kinda). I mean <app-component> and such. They are the root of a component scope for DOM elements (once again, not 100% accurate, this is more to visualize it).

If you want to create custom attributes there are a few ways:

This is the way how you manipulate HTML attributes in Angular (and not only for custom ones)

This adds or removes the attribute from the element

<input [attr.disabled]="!value ? null : '' "

Will result in <input disabled=''> which is the same as <input disabled>. In case we have a value present it would be simply <input>.

And when using [attr. syntax there is I think no limit to the names you can use, outside of what is allowed by Angular.

To make data-attributes:

<div [attr.data-attr-test]=" 'Foo' ">

And simply using a value from the component:

<img [src]="value">

There are also Directives which are placed like attributes but used to manipulate DOM and do behavioural changes:

https://angular.io/guide/attribute-directives

Solution 2:

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.

Post a Comment for "Angular Rendered Dom Html Custom Attributes"