如何将 ngStyle 应用于组件中的 :host 元素?

How to apply ngStyle to :host element in component?

我有这样的东西:

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

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

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

    constructor() {}
}

我想在

上将 属性 columnWidth 应用到 [ngStyle]
<ng-content></ng-content>

父元素,做这样的事情:

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

我知道如何将样式应用于宿主元素:

:host {  /*styles*/  }

但是我不知道给它传递参数

没有办法做到这一点。

你能做的是

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

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

主要限制是 width 部分是固定的,不能从变量中使用。

另一种具有完全灵活性的方法是

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

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

我实际上使用了@GunterZochbauer 的解决方案,但他提到您不能使用变量。也许在那个时候是对的,但有了最新的 angular,你完全可以。

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

我正在使用状态管理来设置宽度,然后将其直接应用于宿主元素。效果很好!