Angular 如何将ngStyle应用于组件中的:主体元素?

Angular 如何将ngStyle应用于组件中的:主体元素?,angular,shadow-dom,angular2-template,Angular,Shadow Dom,Angular2 Template,我有这样的想法: import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'column', template: '<ng-content></ng-content>' }) export class ColumnComponent { @Input() columnWidth: string = '0'; con

我有这样的想法:

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

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

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

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

但我不知道如何将参数传递给它。

没有办法做到这一点

你能做的就是

@HostBinding('style.width'))
宽度:字符串='10px';

@HostBinding('style.width.px'))
宽度:数字='10';
主要限制是
宽度
部分是固定的,不能从变量中使用

另一种具有充分灵活性的方法是

constructor(private-elRef:ElementRef,private-renderer:renderer){
设置样式(){
this.renderer.setElementStyle(this.elRef.nativeElement,'width','10px');
}

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

@HostBinding('style.width.px'))
获取宽度():编号{
返回状态。宽度;
}

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

我有一个错误:无法绑定到“columnWidth”,因为它不是已知的本机属性(“][columnWidth]=”150“>,如果您想将输入值绑定到style
@HostBinding('style.width.px')@input()columnWidth:string='0';
应该可以工作。您尝试了什么?这个答案是10颗星!:)我讨厌我必须一直到渲染器,但这是我能找到的将样式应用到主机的唯一方法,您能否澄清以下语句:“主要限制是宽度部分是固定的,不能从变量中使用。“->我的同事批评了我对
Render2
的使用,并给出了使用
HostBinding
设置变量宽度的示例。
<div [ngStyle]="{'width': columnWidth+'px'}" > ....
:host {  /*styles*/  }