How to apply ngStyle to :host element in component?

Issue

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.

Solution

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

Answered By – Günter Zöchbauer

Answer Checked By – David Goodson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.