我检查了ngStyle,ngClass指令
here,但我仍然无法理解这些是如何工作的:
<div [attr.role]="myAriaRole"> <div [class.extra-sparkle]="isDelightful"> <div [style.width.px]="mySize">
内置指令不选择这样的属性:class.extra-sparkle.什么样的选择器可以选择这样的html属性?哪个内置指令处理这个?
据我所知,dot(style.width.px)的html属性已经不合法了.显然,带方括号的字符串不会直接作为属性传递.但它在哪里完成?哪个指令捕获了这些符号?
解决方法
你是对的,这些不是指令.
Angular编译器为每个具有视图节点的组件创建一个视图工厂.对于每个视图节点,编译器使用位掩码定义一组绑定类型.在变化检测期间执行不同的binding types并因此执行不同类型的操作以反映组件类的变化.
您可能知道允许更新属性的标准输入机制:
<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内部,我强烈建议您阅读:
> 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
由于在更改检测期间处理了所有绑定,因此还读取:
> Everything you need to know about change detection in Angular