[英]How can I create Angular 2 custom attribute directive with dynamic name?
我想以與本示例中使用的內置指令(如“ attr”,“ class”,“ style”)相同的方式創建自定義屬性指令:
<div [style.width.px]="mySize">
此處的文檔僅描述具有固定指令名稱的情況。 所以問題是:
如何為此類指令指定選擇器?
如何獲取指令名稱的變量部分?
還是根本不可能僅將其用於內置指令?
盡管通過@Günter檢查也幾乎可以肯定地做到這一點。
但是,如果您只想要一個與style
幾乎類似的指令,則可能會對您有所幫助。
用法:
<h2 [customStyle]="['width.px', mysize]" >Hello {{name}}</h2>
自定義指令:
@Directive({
selector: '[customStyle]',
inputs: ['style:customStyle']
})
export class CustomDir{
style;
constructor(private elRef: ElementRef){
}
ngAfterViewInit(){
if(this.style){
const prop = this.style[0].split('.')[0];
const unit = this.style[0].split('.')[1];
const val = this.style[1];
this.elRef.nativeElement.style[prop] = val + (unit || '');
}
}
}
據我所知,這不受支持,也沒有計划。
還是根本不可能僅將其用於內置指令?
此語法與指令無關,它是內置綁定語法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.