簡體   English   中英

如何使用動態名稱創建Angular 2自定義屬性指令?

[英]How can I create Angular 2 custom attribute directive with dynamic name?

我想以與本示例中使用的內置指令(如“ attr”,“ class”,“ style”)相同的方式創建自定義屬性指令:

<div [style.width.px]="mySize">

此處的文檔僅描述具有固定指令名稱的情況。 所以問題是:

  1. 如何為此類指令指定選擇器?

  2. 如何獲取指令名稱的變量部分?

還是根本不可能僅將其用於內置指令?

盡管通過@Günter檢查也幾乎可以肯定地做到這一點。


LUN

但是,如果您只想要一個與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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM