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

时间:2021-01-19 17:27:32

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?

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

2 个解决方案

#1


2  

Though it's almost certainely not possible to do this as inspected by @Günter as well.

虽然@Günter检查过几乎不可能做到这一点。


                                                                      PLUNKER ⇗

PLUNKER⇗

But if you just want a directive that works almost similarly to the style, this might help you.

但是,如果您只想要一个与样式几乎相似的指令,这可能会对您有所帮助。

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

#2


0  

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.

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

#1


2  

Though it's almost certainely not possible to do this as inspected by @Günter as well.

虽然@Günter检查过几乎不可能做到这一点。


                                                                      PLUNKER ⇗

PLUNKER⇗

But if you just want a directive that works almost similarly to the style, this might help you.

但是,如果您只想要一个与样式几乎相似的指令,这可能会对您有所帮助。

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

#2


0  

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.

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