Angular 2, используйте переменную в стилях @Component - PullRequest
0 голосов
/ 24 апреля 2018

У меня есть плунжер здесь - https://plnkr.co/edit/fzNJ7FLYxWbLPoxtYpEw?p=preview

Это простое угловое приложение.

Я фиксирую высоту div, используя @ViewChild и nativeElement.offsetHeight

Возможно ли использовать этот номер в блоке стилей компонента.

В моем примере я пытался это сделать, но закомментировал.

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

}

Ответы [ 3 ]

0 голосов
/ 24 апреля 2018

Пользовательская директива [ngStyle].

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

</div>

<div>
  <h2>{{contentHeight}}</h2>

  <div class="blockTwo">

  </div>
</div>
0 голосов
/ 24 апреля 2018

Это можно сделать, используя 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"}
}
0 голосов
/ 24 апреля 2018

вы можете просто сделать это

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

и определить и инициализировать height в вашем файле ts, который будет работать для вас

или какую-то помощь

<div #parentdiv style="background-color:blue;height:1000px">
  <div [ngStyle]="{'max-height.px': parentdiv.offsetHeight}">
    hallo
  </div>
</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...