【问题标题】:Angular 2, use variable in @Component stylesAngular 2,在@Component 样式中使用变量
【发布时间】:2018-04-24 13:34:55
【问题描述】:

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

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

我正在使用 @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;
  }

}

【问题讨论】:

  • 您可以使用这种样式绑定语法:[style.height.px]="contentHeight".

标签: angular


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    用户 [ngStyle] 指令。

    <div class="content" #content [ngStyle]="{'height':'contentHeight'}">
    
    </div>
    
    <div>
      <h2>{{contentHeight}}</h2>
    
      <div class="blockTwo">
    
      </div>
    </div>
    

    【讨论】:

    • 这似乎对我不起作用 - 我需要 '.blockTwo' 来使用高度 - plnkr.co/edit/fzNJ7FLYxWbLPoxtYpEw?p=preview
    • 在您的 plnkr 样式中未定义。使用 elementView 下面的这段代码来定义。 elementView: ElementRef; style:{"height": string};
    【解决方案3】:

    你可以这样做

    //this line is exaple , but point is make use of ngStyle
    <some-element [ngStyle]="{'max-height.px': height}">...</some-element>
    

    并在您的 ts 文件中定义和初始化 height,这将为您工作

    或类似的帮助

    <div #parentdiv style="background-color:blue;height:1000px">
      <div [ngStyle]="{'max-height.px': parentdiv.offsetHeight}">
        hallo
      </div>
    </div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-21
      • 2018-04-08
      • 2016-11-02
      • 2019-07-28
      • 1970-01-01
      • 2019-03-09
      • 2019-10-20
      • 1970-01-01
      相关资源
      最近更新 更多