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

Dar*_*iak 11 shadow-dom angular2-template angular

我有这样的事情:

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

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

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

    constructor() {}
}
Run Code Online (Sandbox Code Playgroud)

我想申请财产columnWidth时[ngStyle]

<ng-content></ng-content>
Run Code Online (Sandbox Code Playgroud)

父元素,做这样的事情:

<div [ngStyle]="{'width': columnWidth+'px'}" > ....
Run Code Online (Sandbox Code Playgroud)

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

:host {  /*styles*/  }
Run Code Online (Sandbox Code Playgroud)

但我不知道将参数传递给它.

Gün*_*uer 20

没有办法做到这一点.

你能做的是

@HostBinding('style.width')
width:string = '10px';
Run Code Online (Sandbox Code Playgroud)

要么

@HostBinding('style.width.px')
width:number = '10';
Run Code Online (Sandbox Code Playgroud)

主要限制是width零件是固定的,不能从变量中使用.

另一种充分灵活的方法是

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

setStyles() {
  this.renderer.setElementStyle(this.elRef.nativeElement, 'width', '10px');
}
Run Code Online (Sandbox Code Playgroud)

  • 如果您想将输入值绑定到样式`@HostBinding('style.width.px')@Input() columnWidth: string = '0';`应该可以。你尝试了什么? (2认同)

chr*_*989 6

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

@HostBinding('style.width.px')
get width(): number {
  return state.width;
}
Run Code Online (Sandbox Code Playgroud)

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