Home > Net >  when is it better to use ngStyle or use a custom directive?
when is it better to use ngStyle or use a custom directive?

Time:12-01

I have to change the column's width dynamically, for to do that I made a custom directive like that:

@Directive({
  selector: '[rq-column-size]'
})

export class ColumnSizeDirective {

  @Input('rq-column-size') set rqColumnSize( width: string) {
    this.eleRef.nativeElement.style.width = width   '%';
  }

  constructor(private eleRef: ElementRef) { }
}

used into HTML:

 <th [rq-column-size]="col.width" ....

the question is:

is it better to use [ngStyle] or my custom directive?

CodePudding user response:

Directive - this is something more complex to just add styling. Directives often used for some logic inside.

But you need only styling here. So, if you need style use [ngStyle], or more in you case [style.width.%]="value".

CodePudding user response:

It is better to use HostBinding:

@Directive({
  selector: '[rq-column-size]'
})

export class ColumnSizeDirective {
  @Input('rq-column-size')
  @HostBinding('style.width.%')
  rqColumnSize: number;
}
  • Related