如何使用动态名称创建Angular 2自定义属性指令

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

本文关键字:Angular 自定义属性 指令 创建 何使用 动态      更新时间:2023-09-26

我想以与本例中使用的"attr"、"class"、"style"等内置指令相同的方式创建自定义属性指令:

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

此处的文档仅描述具有固定指令名称的情况。所以问题是:

  1. 我应该如何为这样的指令指定选择器?

  2. 如何检索指令名称的变量部分?

或者它可能根本不可能,只用于内置指令?

尽管在@Günter的检查中几乎肯定不可能做到这一点。


 nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp nbsp PLUNKER&neArr

但是,如果您只想要一个与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 || '');
    }
  }
}

据我所知,这是不支持的,也没有计划。

或者它可能根本不可能,只用于内置指令?

此语法与指令无关,它是内置的绑定语法。