简体   繁体   English

如何在Angular中编写自定义特殊属性绑定?

[英]How to write a custom special property binding in Angular?

Angular has a feature as special property binding . Angular具有special property binding for example we can use [class.className] or [style.line-height.em] syntax in the property like 例如,我们可以在属性中使用[class.className][style.line-height.em]语法

<!-- isActive() returns true or false in order to set active class -->
<h1 class="leading" [class.active]="isActive()">Title</h1>

<!-- getColor() returns a valid color -->
<h1 [style.color]="getColor()">Title</h1>
<h1 [style.line-height.em]="'2'">Title</h1>

How can I write a custom special property binding? 如何编写自定义特殊属性绑定? for example [my.custom1] or [my.custom2.custom3] or ... 例如[my.custom1][my.custom2.custom3]或......

My question is about these dots How angular handle them? 我的问题是关于这些dots如何角度处理它们?

Is it possible? 可能吗? Any sample? 有样品吗?

The only way to do this is to rename your input. 唯一的方法是重命名输入。 Consider that not as an object notation, but as a whole, exhaustive liste of properties. 考虑不是作为对象表示法,而是作为一个整体,详尽的财产监听。

@Input('my.custom2') myCustom2: any;
@Input('my.custom3') myCustom3: any;

For an example, you can look at @angular/flex-layout , which uses this notation (go at line 65) 例如,您可以查看使用此表示法的@angular/flex-layout (转到第65行)

EDIT Angular isn't "dynamic", they rely on Javascript to get those attributes. 编辑 Angular不是“动态的”,他们依靠Javascript来获取这些属性。 This is built in the framework and it isn't exposed for you to use. 这是在框架中构建的,它不会暴露给您使用。 Look at this : 看这个 :

 const el = document.querySelector('div'); console.log(el.attributes[0].name); 
 <div class.myClass="true"></div> 

As you can see, you can get the attributes this way. 如您所见,您可以通过这种方式获取属性。 Angular doesn't provide a way to select attribute "dynamically". Angular没有提供一种“动态”选择属性的方法。 It just offers one or two custom attribute reading like class or attr , but that's all. 它只提供一个或两个自定义属性读取,如classattr ,但这就是全部。

For instance, a quick search in github's Angular repo will confirm this on this file (line 161), this file (line 276), this file (line 67), and probably much more (I only checked first 3 pages of the search result). 例如,在github的Angular repo中快速搜索将在此文件 (第161行), 此文件 (第276行), 此文件 (第67行)以及可能更多(我只检查搜索结果的前3页)中确认)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM