Подтвердить что ты не робот

Динамическое обновление css в Angular 2

Скажем, у меня есть Angular2 Component

//home.component.ts

import { Component } from 'angular2/core';

@Component({
    selector: "home",
    templateUrl: "app/components/templates/home.component.html",
    styleUrls: ["app/components/styles/home.component.css"]
})
export class HomeComponent {
    public width: Number;
    public height: Number;
} 

Шаблон html файла для этого компонента

//home.component.html

<div class="home-component">Some stuff in this div</div>

И наконец, файл css для этого компонента

//home.component.css

.home-component{
    background-color: red;
    width: 50px;
    height: 50px;
}

Как вы видите, в классе есть 2 свойства, width и height. Я хотел бы, чтобы стили css для ширины и высоты соответствовали значениям свойств ширины и высоты и при обновлении свойств, ширине и высоте обновления div. Каков правильный способ сделать это?

4b9b3361

Ответ 1

Попробуйте это

 <div class="home-component" 
 [style.width.px]="width" 
 [style.height.px]="height">Some stuff in this div</div>

[Обновлено]: Чтобы установить в% используйте

[style.height.%]="height">Some stuff in this div</div>

Ответ 2

Чтобы использовать% вместо px или em с ответом @Gaurav, просто

<div class="home-component" [style.width.%]="80" [style.height.%]="95">
Some stuff in this div</div>

Ответ 3

Это должно сделать это:

<div class="home-component" 
     [style.width]="width + 'px'" 
     [style.height]="height + 'px'">Some stuff in this div</div>

Ответ 4

Проверьте рабочую демонстрацию здесь

import {Component,bind} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
import {FORM_DIRECTIVES} from 'angular2/form';

import {Directive, ElementRef, Renderer, Input,ViewChild,AfterViewInit} from 'angular2/core';

@Component({
  selector: 'my-app',
    template: `
    <style>
       .myStyle{
        width:200px;
        height:100px;
        border:1px solid;
        margin-top:20px;
        background:gray;
        text-align:center;
       }
    </style>

          <div [class.myStyle]="my" [style.background-color]="randomColor" [style.width]="width+'px'" [style.height]="height+'px'"> my width={{width}} & height={{height}}</div>
    `,
    directives: []
})

export class AppComponent {
  my:boolean=true;
  width:number=200px;
  height:number=100px;
  randomColor;
  randomNumber;
  intervalId;
  textArray = [
    'blue',
    'green',
    'yellow',
    'orange',
    'pink'
  ];


  constructor() 
  {
    this.start();
  }

      start()
      { 
        this.randomNumber = Math.floor(Math.random()*this.textArray.length);
        this.randomColor=this.textArray[this.randomNumber];
        console.log('start' + this.randomNumber);
        this.intervalId = setInterval(()=>{
         this.width=this.width+20;
         this.height=this.height+10;
         console.log(this.width +" "+ this.height)
         if(this.width==300)
         {
           this.stop();
         }

        }, 1000);
      }
      stop()
      {
        console.log('stop');
        clearInterval(this.intervalId);
        this.width=200;
        this.height=100;
        this.start();

      }
 }

bootstrap(AppComponent, []);

Ответ 5

Вы можете динамически изменять стиль (ширину и высоту) div, добавляя динамическое значение к inline [style.width] и свойству [style.hiegh] div.

В вашем случае вы можете связать свойство width и height класса HomeComponent с свойством width и height стиля div inline, подобным этому...   Как указано Sasxa

<div class="home-component" 
     [style.width]="width + 'px'" 
     [style.height]="height + 'px'">Some stuff in this div
</div>

Для рабочей демонстрации посмотрите на этот плункер (http://plnkr.co/edit/cUbbo2?p=preview)

   //our root app component
import {Component} from 'angular2/core';
import {FORM_DIRECTIVES,FormBuilder,AbstractControl,ControlGroup,} from "angular2/common";

@Component({
  selector: 'home',
  providers: [],
  template: `
     <div class="home-component" [style.width]="width+'px'" [style.height]="height+'px'">Some this div</div>
     <br/>
     <form [ngFormModel]="testForm">
        width:<input type="number" [ngFormControl]="txtWidth"/> <br>
        Height:<input type="number"[ngFormControl]="txtHeight" />
     </form>
  `,
  styles:[`

      .home-component{
        background-color: red;
        width: 50px;
        height: 50px;
    }

  `],
  directives: [FORM_DIRECTIVES]
})
export class App {
  testForm:ControlGroup;
  public width: Number;
  public height: Number;
  public txtWidth:AbstractControl;
  public txtHeight:AbstractControl;

  constructor(private _fb:FormBuilder) {
      this.testForm=_fb.group({
        'txtWidth':['50'],
        'txtHeight':['50']
      });

      this.txtWidth=this.testForm.controls['txtWidth'];
      this.txtHeight=this.testForm.controls['txtHeight'];

      this.txtWidth.valueChanges.subscribe(val=>this.width=val);
      this.txtHeight.valueChanges.subscribe(val=>this.height =val);
  }
}

Ответ 6

Вы также можете использовать hostbinding:

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

export class HomeComponent {
    @HostBinding('style.width') width: Number;
    @HostBinding('style.height') height: Number;
} 

Теперь, когда вы изменяете свойство width или height из HomeComponent, это должно влиять на атрибуты стиля.

Ответ 7

Все вышеперечисленные ответы велики. Но если вы пытаетесь найти решение, которое не изменит файлы html ниже, полезно

 ngAfterViewChecked(){
    this.renderer.setElementStyle(targetItem.nativeElement, 'height', textHeight+"px");
}

Вы можете импортировать рендерер из import {Renderer} from '@angular/core';

Ответ 8

Мне понравился вид WenhaoWuI выше, но мне нужно было идентифицировать div с классом ".ui-tree" в компоненте дерева PrimeNG, чтобы динамически установить высоту. Все ответы, которые я мог найти, требовали, чтобы имя div (т.е. #treediv), чтобы включить использование @ViewChild(), @ViewChildren(), @ContentChild(), @ContentChilden() и т.д. Это было грязно с третьей стороной компонент.

Наконец-то я нашел фрагмент из Günter Zöchbauer:

ngAfterViewInit() {
  this.elRef.nativeElement.querySelector('.myClass');
}

Это упростило:

@Input() height: number;
treeheight: number = 400; //default value

constructor(private renderer: Renderer2, private elRef: ElementRef) {  }

ngOnInit() {
    this.loading = true;
    if (this.height != null) {
        this.treeheight = this.height;
    }   
}

ngAfterViewInit() {
    this.renderer.setStyle(this.elRef.nativeElement.querySelector('.ui-tree'), 'height', this.treeheight + "px");
}