Angular set css style for:host in ngOnInit

时间:2017-08-18 08:01:54

标签: angular

我不知道如何在组件中的ngOnInit中为:host {}设置css样式。 可以使用Renderer来设置吗?

示例:

<app-a *ngFor ="let a in alist" [a] = "a"></app-a>

在ngOnInit app-a中我想设置宽度高度样式的百分比:app-a的主机在被ngFor渲染时的组件?

我可以这样做吗?

非常感谢。

2 个答案:

答案 0 :(得分:5)

您还可以使用@HostBinding装饰器,如:

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

@Component({
  selector: 'my-app',
  templateUrl: `./app.component.html`
})
export class AppComponent {
  @HostBinding('style.display') display: string;
  @HostBinding('style.width.%') width: number;
  @HostBinding('style.height.px') height: number;

  ngOnInit() {
    this.display = 'block';
    this.width = 50;
    this.height = 500;
  }
}

答案 1 :(得分:2)

您通常在组件装饰器中以声明方式设置样式:

@Component({
   styles: [':host { display: block; }']
});
export class AppComponent {}

但如果你真的需要从ngOnInit那样做,你可以插入主机元素并使用渲染器:

export class AppComponent {
  constructor(private host: ElementRef, private renderer: Renderer2) {  }

  ngOnInit() {
    this.renderer.setStyle(this.host.nativeElement, 'display', 'block');
  }
相关问题