Actualización dinámica de css en Angular 2


Digamos que tengo un componente Angular2

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

El archivo html de plantilla para este componente

//home.component.html

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

Y finalmente el archivo css para este componente

//home.component.css

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

Como puedes ver, hay 2 propiedades en la clase, width y height. Me gustaría que los estilos css para width y height coincidieran con los valores de las propiedades width y height y cuando las propiedades se actualicen, el ancho y la altura de la actualización div. ¿Cuál es la manera apropiada de lograr esto?

 66
Author: tt9, 2016-03-09

9 answers

Prueba esto

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

[Actualizado]: Para establecer en % use

[style.height.%]="height">Some stuff in this div</div>
 154
Author: Gaurav Mukherjee,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-12 07:44:29

Para usar % en lugar de px o em con la respuesta de @Gaurav, es solo

<div class="home-component" [style.width.%]="80" [style.height.%]="95">
Some stuff in this div</div>
 39
Author: Helen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-13 01:44:00

Esto debería hacerlo:

<div class="home-component" 
     [style.width]="width + 'px'" 
     [style.height]="height + 'px'">Some stuff in this div</div>
 14
Author: Sasxa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-09 04:09:41

También puede usar hostbinding:

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

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

Ahora, cuando cambie la propiedad width o height desde el componente principal, esto debería afectar a los atributos de estilo.

 10
Author: 11mb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-13 14:12:11

Compruebe Demo aquí

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, []);
 6
Author: micronyks,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-09 05:23:11

Puede cambiar dinámicamente el estilo(ancho y alto) de div adjuntando un valor dinámico a inline [style.ancho] y [estilo.hiegh] propiedad de div.

En su caso, puede enlazar la propiedad width y height de la clase HomeComponent con la propiedad inline style width y height del div como esta... Según las indicaciones de Sasxa

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

Para la demostración de trabajo, eche un vistazo a este émbolo ( 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);
  }
}
 4
Author: Jorin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-09 06:11:20

Todas las respuestas anteriores son geniales. Pero si usted estaba tratando de encontrar una solución que no va a cambiar los archivos html a continuación es útil

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

Puede importar el renderizador desde import {Renderer} from '@angular/core';

 3
Author: WenhaoWu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-23 11:05:19

Me gustó el aspecto de la idea de WenhaoWuIanterior, pero necesitaba identificar el div con clase".ui-tree " en el Componente de árbol PrimeNG para establecer la altura dinámicamente. Todas las respuestas que pude encontrar requerían que se nombrara el div (es decir, #treediv) para habilitar el uso de @ViewChild (), @ViewChildren (), @ContentChild (), etc. Esto fue complicado con un componente de terceros.

Finalmente encontré un fragmento de Günter Zöchbauer :

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

Esto lo hizo fácil:

@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");
}
 1
Author: davaus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-22 01:57:34

La respuesta aceptada no es incorrecta.

Para estilos agrupados también se puede usar la directiva ngStyle.

<some-element [ngStyle]="{'font-style': styleExpression, 'font-weight': 12}">...</some-element>

Los documentos oficiales están aquí

 1
Author: JoshuaTree,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-13 07:58:22