Angular 2,在@Component样式中使用变量

标签 angular

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

这是一个简单的 Angular 应用程序。

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

是否可以在组件的样式 block 中使用这个数字。

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

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

}

最佳答案

这可以使用 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"}
}

关于Angular 2,在@Component样式中使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50003067/

相关文章:

javascript - Angular2 文档 - 分层依赖注入(inject)器(恢复服务)

angular - 使用 ngserve 时在 Angular 类中编译时出错

javascript - 如何使用 Jasmine 测试 Angular 6 中包含在 ng-container 中的元素?

Angular2 RxJS - 为模拟服务创建可观察对象

javascript - 如何在 Angular2 中使用/包含 fabricjs

javascript - 无法在 setTimeout 函数下获取组件变量

angular - 如何在.html(不是.ts)中调用其他类的静态方法?

angular - NullInjectorError : No provider for InjectionToken NGX_ECHARTS_CONFIG

angular - 如何在firebase中将电子邮件验证码发送到用户电子邮件

javascript - "map((respone) => respone.json())"和 "map((respone) =>{ respone.json();})"之间的区别