How to apply ngStyle to :host element in component?

Dariusz Filipiak picture Dariusz Filipiak · May 25, 2016 · Viewed 7.5k times · Source

I have something like this:

import { Component, OnInit, Input } from '@angular/core';

@Component({
    selector: 'column',
    template: '<ng-content></ng-content>'
})
export class ColumnComponent {

    @Input() columnWidth: string = '0';        

    constructor() {}
}

and I wanna apply property columnWidth to [ngStyle] on

<ng-content></ng-content>

parent element, to do something like this:

<div [ngStyle]="{'width': columnWidth+'px'}" > ....

I know how to apply style to host element:

:host {  /*styles*/  }

but I don't know to pass parameters to it.

Answer

G&#252;nter Z&#246;chbauer picture Günter Zöchbauer · May 25, 2016

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');
}