Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply ngStyle to :host element in component?

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.

like image 738
Dariusz Filipiak Avatar asked May 25 '16 12:05

Dariusz Filipiak


People also ask

How we can add style to the particular component in Angular?

There are several ways to add styles to a component: By setting styles or styleUrls metadata. Inline in the template HTML. With CSS imports.

What is the use of ngStyle directive?

The NgStyle directive lets you set a given DOM elements style properties. This sets the background color of the div to green. The above code uses the ternary operator to set the background color to green if the persons country is the UK else red.

How do I use ngStyle in Angular 9?

Use property binding to style one CSS property of an element and use the ngStyle directive to set multiple CSS properties. ngStyle is applied as an attribute to an element. The square brackets around the directive indicate that the NgStyle directive has an input property also called ngStyle.


1 Answers

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');
}
like image 94
Günter Zöchbauer Avatar answered Sep 18 '22 14:09

Günter Zöchbauer