How to apply ngStyle to :host element in component?

I actually used @GunterZochbauer 's solution but he mentioned that you cannot use a variable. Maybe at that time that was right but with the latest angular, you totally could.

@HostBinding('style.width.px')
get width(): number {
  return state.width;
}

I'm using state management to set the width and then apply it directly to the host element. It works great!


There is no way to do this.

What you can do is

@HostBinding('style.width')
width:string = '10px';

or

@HostBinding('style.width.px')
width:number = '10';

The main limitation is that the width part is fixed and can't be used from a variable.

Another way with full flexibility is

constructor(private elRef:ElementRef, private renderer:Renderer) {}

setStyles() {
  this.renderer.setElementStyle(this.elRef.nativeElement, 'width', '10px');
}