简体   繁体   中英

How to write a custom special property binding in Angular?

Angular has a feature as special property binding . for example we can use [class.className] or [style.line-height.em] syntax in the property like

<!-- 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 question is about these dots How angular handle them?

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)

EDIT Angular isn't "dynamic", they rely on Javascript to get those attributes. 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". It just offers one or two custom attribute reading like class or attr , but that's all.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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