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

问题描述 投票:10回答:2

我有这样的事情:

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*/  }

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

angular shadow-dom angular2-template
2个回答
17
投票

没有办法做到这一点。

你能做的是

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

1
投票

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

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

我正在使用状态管理来设置宽度,然后将其直接应用于host元素。它很棒!

© www.soinside.com 2019 - 2024. All rights reserved.