2

I want to create a directive with a semi-dynamic selector.

Angular team use this approach in some places, for example [style.width.px]="100" and (keyup.enter)="doSomething()".

There is a way to do this in my custom directive? Something like [my-directive.some-data]="variable".

PMO1948
  • 2,210
  • 11
  • 34
Shalom Peles
  • 2,285
  • 8
  • 21

2 Answers2

0

You can add an @Input() to your directive, though the syntax is slightly different from what you wrote.

so you could do something like

<p myDirective [someData]="variable">lorem ipsum</p>

Check out the angular docs for more information

EDIT: If you want to see an example with multiple inputs, check out this answer here

PMO1948
  • 2,210
  • 11
  • 34
0

After publish the answer, I think that really it's not what are you looking for, but....you can create a directive like:

@Directive({
  selector: '[mydirective.one],[mydirective.two],[mydirective.three]'
})
export class MyDirective implements OnInit {
  @Input('mydirective.one') prop1
  @Input('mydirective.two') prop2
  @Input('mydirective.three') prop3

  constructor(private el:ElementRef,private renderer:Renderer2) {}
   ngOnInit()
   {
    console.log(this.prop1,this.prop2,this.prop3)
    if (this.prop1)
       this.renderer.setStyle(this.el.nativeElement,"background-color",prop1)

    if (this.prop2)
       this.renderer.setStyle(this.el.nativeElement,"color",prop2)

    if (this.prop3)
       this.renderer.setStyle(this.el.nativeElement,"font-size",prop3)

   }
}

See how the selectors can be sepatated by commas, and you need use the way @Input(name.prop) variable because you can not use a variable separated by dot

Update perfahs you are looking for host. You can declare a directive like

@Directive({
  selector: '[mydirective]',
  host:{'[class.active]':'value'}
})
export class MyDirective {
  value:boolean=false;
  @Input() set mydirective(value)
  {
      this.value=value;
  }
Eliseo
  • 50,109
  • 4
  • 29
  • 67