首页 > 解决方案 > Angular 2,在@Component 样式中使用变量

问题描述

我在这里有一个 plunker - https://plnkr.co/edit/fzNJ7FLYxWbLPoxtYpEw?p=preview

它是一个简单的角度应用程序。

我正在使用 @ViewChild 和 nativeElement.offsetHeight 捕获 div 的高度

是否可以在组件的样式块中使用此数字。

在我的示例中,我尝试过但将其注释掉。

@Component({
  selector: 'my-app',
  templateUrl: './src/app.html',
  styles: [`
    .blockTwo {
      background: yellow;
      //height: this.contentHeight+px;
      height: 200px;
    }
  `]
})

=

import {Component, ElementRef, ViewChild, AfterViewInit} from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './src/app.html',
  styles: [`
    .blockTwo {
      background: yellow;
      //height: this.contentHeight+px;
      height: 200px;
    }
  `]
})

export class AppComponent implements AfterViewInit{

  @ViewChild('content') 
  elementView: ElementRef;

  contentHeight: number;

  constructor() {

  }

  ngAfterViewInit() {
      this.contentHeight = this.elementView.nativeElement.offsetHeight;
  }

}

标签: angular

解决方案


这可以使用 ngStyle

在您的 app.html 中,将黄色 div 更改为:

<div class="blockTwo" [ngStyle]="style">
</div>

在你的 app.ts

style: any;
ngAfterViewInit() {
  this.contentHeight = this.elementView.nativeElement.offsetHeight;
  this.style = {"height": this.contentHeight+"px"}
}

推荐阅读