How [class] [attr] [style] directives work

I reviewed the ngStyle, ngClass directives here , but I still could not understand how they work:

<div [attr.role]="myAriaRole">
<div [class.extra-sparkle]="isDelightful">
<div [style.width.px]="mySize">

Embedded directives are not selected this attribute: class.extra-sparkle. What type selectorcan this html attribute choose? Which inline directive does this?

As far as I know, html attributes with dot ( style.width.px) are no longer legal. Apparently, a line with square brackets is not passed directly as attributes. But where is this done? What directive catches these notations?

+4
source share
3 answers

You are right, these are not directives.

Compiler

Angular factory . node . , , , , .

, , :

<div [prop]="myAriaRole">

TypeProperty :

TypeProperty = 1 << 3

, , .

attr.*, class.* style.* :

TypeElementAttribute = 1 << 0,
TypeElementClass = 1 << 1,
TypeElementStyle = 1 << 2,

:

function CheckAndUpdateElement() {
    ...
    case BindingFlags.TypeElementAttribute -> setElementAttribute
    case BindingFlags.TypeElementClass     -> setElementClass
    case BindingFlags.TypeElementStyle     -> setElementStyle
    case BindingFlags.TypeProperty         -> setElementProperty;

Angular, , :

, :

+4

Angular.io docs.

, .

<img [src]="heroImageUrl">

div .

<table>
    <tr><td [attr.colspan]="1 + 1">One-Two</td></tr>
</table>

div .

<!-- toggle the "special" class on/off with a property -->
<div [class.special]="isSpecial">The class binding is special</div>

<!-- binding to `class.special` trumps the class attribute -->
<div class="special"
     [class.special]="!isSpecial">This one is not so special</div>

NgClass.

div . , div (, , Angular).

<button [style.color]="isSpecial ? 'red': 'green'">Red</button>
<button [style.background-color]="canSave ? 'cyan': 'grey'" >Save</button>

NgStyle.

, . ( class, , isDelightful true.)

<div [attr.role]="myAriaRole"></div>
<div [class.extra-sparkle]="isDelightful"></div>
<div [style.width.px]="mySize"></div>

- Stackblitz, .:)

+2

@Edric , . ,

[attr.role]
[class.extra-sparkle]
[style.width.px]

ngClass ngStyle, . , :

bind-attr.role
bind-class.extra-sparkle
bind-style.width.px

and the prefix bindings are compiled into the template parser here . "Bind thing" is not a directive, it is a built-in function in which the compiler already processes all related properties, attributes, etc. .

+2
source

Source: https://habr.com/ru/post/1687112/


All Articles