1

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?

2 Answers 2

2

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 || '');
    }
  }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Is it possible to have multiple of customStyle attributes in one tag like with style.* binding?
unfortunately NO. but you can always modify it to accept more than one styling just like ngStyle
One more question. Why setTimeout() is needed your code?
Oh I left it there by mistake, initially I was using OnInit hook where manual change detection trigger is required, but now it's not. sorry, removing..
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.