0

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?

slacky82
  • 342
  • 4
  • 11
  • There is a security risk when using elementref [elementref-security-risk-angular-2](https://stackoverflow.com/questions/42834226/elementref-security-risk-angular-2), in this case, you are using elementref to modify the DOM which is not good. try to use [Renderer2#setStyle](https://angular.io/api/core/Renderer2#setStyle). – HDJEMAI Nov 30 '21 at 15:37

2 Answers2

0

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".

Anton Marinenko
  • 2,749
  • 1
  • 10
  • 16
0

To change the style directly on the component there are two methods HostBinding or Renderer2. If your Input changes, you need to update it every time with 'Render2' but with HostBinding this is done automatically and the syntax is much cleaner.

that's why it's better to use HostBinding

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

export class ColumnSizeDirective {
  @Input('rq-column-size')
  @HostBinding('style.width.%')
  rqColumnSize: number;
}
Chris
  • 2,117
  • 13
  • 18
  • why is it better? – AT82 Dec 01 '21 at 08:55
  • @AT82 to change style directly on the component there are two methods HostBinding or Renderer2. but if your input changes you have to update it every time with render2 but HostBinding does this automatically and the syntax is much cleaner – Chris Dec 03 '21 at 10:35
  • 1
    Well I'd suggest that you update that in your answer then instead of just having *It's better to use...* without any eplanation :) – AT82 Dec 03 '21 at 10:37