首页 文章

动态更新Angular 2中的css

提问于
浏览
80

假设我有一个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更新的宽度和高度 . 完成此任务的正确方法是什么?

10 回答

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

    要使用%而不是px或em与@Gaurav的答案,它只是

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

    这应该这样做:

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

    您还可以使用hostbinding:

    import { HostBinding } from '@angular/core';
    
    export class HomeComponent {
        @HostBinding('style.width') width: Number;
        @HostBinding('style.height') height: Number;
    }
    

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

  • 2

    Check working Demo here

    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, []);
    
  • 4

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

    在您的情况下,您可以将HomeComponent类的width和height属性与div的内联样式width和height属性绑定,如下所示... As directed by Sasxa

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

    有关工作演示,请查看此plunker(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>
         
    <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

    以上所有答案都很棒 . 但是,如果你试图找到一个不会改变下面的html文件的解决方案是有帮助的

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

    您可以从 import {Renderer} from '@angular/core'; 导入渲染器

  • 189

    接受的答案并不正确 .

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

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

    官方文档是here

  • 42

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

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

    我喜欢上面的 WenhaoWuI 的想法,但我需要在 PrimeNG tree component 中用 class .ui-tree 识别div来动态设置高度 . 我能找到的所有答案都需要命名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");
    }
    

相关问题