在Angular 2中动态更新CSS


108

假设我有一个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;
} 

该组件的模板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个属性widthheight。我希望宽度和高度的css样式与width和height属性的值匹配,并且当属性更新时,div的宽度和高度也会更新。完成此操作的正确方法是什么?

Answers:


264

试试这个

 <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>

50

要在@Gaurav的答案中使用%而不是px或em,这只是

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

18

应该这样做:

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

11

您还可以使用主机绑定:

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

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

现在,当您从HomeComponent中更改width或height属性时,这应该会影响样式属性。


7

接受的答案不正确。

对于分组样式,也可以使用ngStyle指令。

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

官方文档在这里


6

在这里检查工作演示

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

如果要使用变量动态设置宽度,而不是使用[]大括号而不是{{}}:

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

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

5

您可以通过将动态值附加到div的内联[style.width]和[style.hiegh]属性来动态更改div的样式(宽度和高度)。

在您的情况下,您可以将HomeComponent类的width和height属性与div的内联样式的width和height属性进行绑定,如下所示: 按照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);
  }
}

5

我喜欢上面的WenhaoWuI想法,但我需要在PrimeNG树组件中使用 来标识div以动态设置高度。所有我能找到答案所需的div来命名(即#treediv),允许使用的,,,.ui-tree@ViewChild()@ViewChildren()@ContentChild()@ContentChilden()等这是凌乱与第三方组件。

我终于从GünterZö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");
}

4

以上所有答案都很不错。但是,如果您试图找到不会更改以下html文件的解决方案,则将很有帮助

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

您可以从 import {Renderer} from '@angular/core';


1
自发布此答案以来,不推荐使用Renderer。请改用Renderer2,然后将setElementStyle()替换为setStyle()
克里斯,

2

您也可以通过调用函数来实现

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

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

0

在HTML中:

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

在Ts

this.maxHeightForScrollContainer = 200 //your custom maxheight
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.