vagran
vagran

Reputation: 1012

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:

<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?

Upvotes: 1

Views: 650

Answers (2)

Ankit Singh
Ankit Singh

Reputation: 24945

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


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

Upvotes: 2

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657396

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.

Upvotes: 0

Related Questions