简体   繁体   English

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

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

I want to create custom attribute directive in the same manner how it is done for built-in directives like "attr", "class", "style" used as in this example: 我想以与本示例中使用的内置指令(如“ attr”,“ class”,“ style”)相同的方式创建自定义属性指令:

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

The documentation here describes only the case with a fixed directive name. 此处的文档仅描述具有固定指令名称的情况。 So the questions are: 所以问题是:

  1. How should I specify selector for such directive? 如何为此类指令指定选择器?

  2. How can I retrieve the variable part of the directive name? 如何获取指令名称的变量部分?

Or may be it is not possible at all and used only for built-in directives? 还是根本不可能仅将其用于内置指令?

Though it's almost certainely not possible to do this as inspected by @Günter as well. 尽管通过@Günter检查也几乎可以肯定地做到这一点。


PLUNKER ⇗ LUN

But if you just want a directive that works almost similarly to the style , this might help you. 但是,如果您只想要一个与style几乎类似的指令,则可能会对您有所帮助。

Usage: 用法:

<h2 [customStyle]="['width.px', mysize]" >Hello {{name}}</h2>

Custom Directive: 自定义指令:

@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 || '');
    }
  }
}

This is not supported and also not planned as far as I know. 据我所知,这不受支持,也没有计划。

Or may be it is not possible at all and used only for built-in directives? 还是根本不可能仅将其用于内置指令?

This syntax is not related to directives, it is built-in binding syntax. 此语法与指令无关,它是内置绑定语法。

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

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