Angular 2'de dinamik olarak css güncelleme


108

Diyelim ki bir Angular2 Bileşenim var

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

Bu bileşen için şablon html dosyası

//home.component.html

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

Ve son olarak bu bileşen için css dosyası

//home.component.css

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

Gördüğünüz gibi sınıfta 2 özellik var widthve height. Genişlik ve yükseklik için css stillerinin genişlik ve yükseklik özelliklerinin değerleriyle eşleşmesini ve özellikler güncellendiğinde, div'in genişlik ve yüksekliğinin güncellenmesini istiyorum. Bunu başarmanın doğru yolu nedir?

Yanıtlar:


265

Bunu dene

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

[Güncellendi]: Kullanım yüzdesini ayarlamak için

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

51

@ Gaurav'ın cevabında px veya em yerine% kullanmak, sadece

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

18

Bunu yapmalı:

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

11

Ayrıca ana bilgisayar bağlamayı da kullanabilirsiniz:

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

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

Şimdi, genişlik veya yükseklik özelliğini HomeComponent içinden değiştirdiğinizde, bu, stil niteliklerini etkilemelidir.


7

Kabul edilen cevap yanlış değil.

Gruplanmış stiller için ngStyle yönergesi de kullanılabilir.

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

Resmi belgeler burada


6

Çalışma Demosunu buradan kontrol edin

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

Genişliği değişkenle dinamik olarak ayarlamak istiyorsanız, bunun yerine [] parantez kullanın {{}}:

 <div [style.width.px]="[widthVal]"  [style.height.px]="[heightVal]"></div>

 <div [style.width.%]="[widthVal]"  [style.height.%]="[heightVal]"></div>

5

Div'in satır içi [style.width] ve [style.hiegh] özelliğine dinamik değer ekleyerek div stilini (genişlik ve yükseklik) dinamik olarak değiştirebilirsiniz.

Sizin durumunuzda, HomeComponent sınıfının width ve height özelliğini div'in satır içi stili width ve height özelliği ile şu şekilde bağlayabilirsiniz ... Sasxa tarafından yönetildiği gibi

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

Çalışma demosu için şu plunker'a bir göz atın ( 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);
  }
}

5

Ben görünümünü sevdim WenhaoWuI yukarıda 'ın fikri, ama birlikte div tanımlamak için gerekli sınıfının .ui-tree içinde PrimeNG ağaç bileşeni dinamik yüksekliğini ayarlamak için. Bütün cevaplar ı kullanımını etkinleştirmek için (yani #treediv) ismini vermek div gerekli bulabildiğim @ViewChild(), @ViewChildren(), @ContentChild(), @ContentChilden()vb Bu üçüncü şahıs bileşeni ile dağınık oldu.

Sonunda Günter Zöchbauer'den bir pasaj buldum :

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

Bu, işi kolaylaştırdı:

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

4

Yukarıdaki cevapların tümü harika. Ancak, aşağıdaki html dosyalarını değiştirmeyecek bir çözüm bulmaya çalışıyorsanız yardımcı olacaktır

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

Oluşturucuyu şuradan içe aktarabilirsiniz: import {Renderer} from '@angular/core';


1
Bu yanıt gönderildiği için Renderer kullanımdan kaldırıldı. Kullanım Renderer2 yerine ve setStyle tarafından setElementStyle () () yerine
Chris

2

bir işlevi de arayarak bunu başarabilirsiniz

<div [style.width.px]="getCustomeWidth()"></div>

  getCustomeWidth() {
    //do what ever you want here
    return customeWidth;
  }

0

Html'de:

<div [style.maxHeight]="maxHeightForScrollContainer + 'px'">
</div>

TS olarak

this.maxHeightForScrollContainer = 200 //your custom maxheight
Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.