[class] [attr] [style]指令如何工作 [英] How [class] [attr] [style] directives work

查看:72
本文介绍了[class] [attr] [style]指令如何工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我检查了ngStyle,ngClass指令此处,但我仍然不明白它们是如何工作的:

I examined ngStyle, ngClass directives here but I still couldn't understand how these work:

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

内置指令不会选择这样的属性:class.extra-sparkle.哪种selector可以选择这样的html属性?哪个内置指令可以处理此问题?

Built-in directives don't select such an attribute: class.extra-sparkle. What kind of selector can select such html attribute? Which built-in directive handles this?

据我所知,带点(style.width.px)的html属性已经不合法了.显然,带有方括号的字符串不会直接作为属性传递.但是,在哪里完成的呢?哪个指令可以捕获这些符号?

As far as I know html attributes with dot (style.width.px) are not legal already. Apparently the string withing square brackets don't passed directly as attributes. But where it is done? Which directive catches these notations?

推荐答案

是的,这些不是指令.

You're right, these are not directives.

Angular编译器为具有视图节点的每个组件创建一个视图工厂.对于每个视图节点,编译器使用位掩码定义一组绑定类型.有不同的绑定类型并因此在更改检测期间执行不同类型的操作以反映组件类中的更改.

Angular compiler creates a view factory for each component with view nodes. For each view node the compiler defines a set of bindings types using the bitmask. There are different binding types and hence different types of operations performed during change detection to reflect changes in the component class.

您可能知道允许更新属性的标准输入机制:

You probably know about the standard input mechanism that allows updating the property:

<div [prop]="myAriaRole">

编译器为其创建TypeProperty绑定:

TypeProperty = 1 << 3

,因此在更改检测期间将使用更新元素属性的操作.

and hence the operation to update the element property is used during change detection.

特殊语法attr.*class.*style.*定义了不同的绑定类型:

The special syntax attr.*, class.* and style.* defines different type of bindings:

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

因此,在更改检测期间,每种绑定类型都使用了相应的操作:

so during change detection for each type of binding corresponding operation is used:

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

要了解有关视图和绑定的Angular内部知识,我强烈建议阅读:

To learn about Angular internals related to view and bindings I strongly recommend reading:

  • The mechanics of DOM updates in Angular
  • The mechanics of property bindings update in Angular
  • Here is why you will not find components inside Angular

由于更改检测期间处理了所有绑定,因此请阅读:

Since all bindings are processed during change detection also read:

这篇关于[class] [attr] [style]指令如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆