【问题标题】:Dynamically updating css in Angular 2在 Angular 2 中动态更新 css
【发布时间】:2016-06-23 07:13:45
【问题描述】:

假设我有一个 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 样式与宽度和高度属性的值相匹配,并且当属性更新时,div 的宽度和高度也会更新。实现此目的的正确方法是什么?

【问题讨论】:

    标签: css angular


    【解决方案1】:

    应该这样做:

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

    【讨论】:

      【解决方案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, []);
      

      【讨论】:

        【解决方案3】:

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

        在您的情况下,您可以将 HomeComponent 类的宽度和高度属性与 div 的内联样式宽度和高度属性绑定,如下所示... 由 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>
             <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】:

          试试这个

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

          【讨论】:

          • 哇!太简单了!
          • 你能帮我告诉我为什么[style.marginLeft.%]="this.triangleMargin" 不起作用吗? :( 其他部分就像你向我们展示的那样工作,谢谢 :)
          • 如果我要进行操作,我可以这样做吗,[style.height.px]="someVariable * 5"
          • 到@Siminho 不要使用这个。它隐含在 html 模板中。
          【解决方案5】:

          您也可以使用主机绑定:

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

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

          【讨论】:

          • 您能解释一下如何使用这些宽度和高度变量吗?什么是 diff b/w normal width: number 和 @HostBinding ?
          【解决方案6】:

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

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

          【讨论】:

            【解决方案7】:

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

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

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

            【讨论】:

            • 自发布此答案以来,渲染器已被弃用。改用 Renderer2,并将 setElementStyle() 替换为 setStyle()
            • 不错!这是我的选择
            【解决方案8】:

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

            我终于从Günter Zöchbauer找到了一个sn-p:

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

            【讨论】:

              【解决方案9】:

              接受的答案没有错误。

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

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

              官方文档是here

              【讨论】:

                【解决方案10】:

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

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

                【讨论】:

                  【解决方案11】:

                  你也可以通过调用函数来实现这一点

                  <div [style.width.px]="getCustomeWidth()"></div>
                  
                    getCustomeWidth() {
                      //do what ever you want here
                      return customeWidth;
                    }
                  

                  【讨论】:

                    【解决方案12】:

                    在 HTML 中:

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

                    在 Ts 中

                    this.maxHeightForScrollContainer = 200 //your custom maxheight
                    

                    【讨论】:

                      猜你喜欢
                      • 2018-02-24
                      • 2017-10-22
                      • 1970-01-01
                      • 1970-01-01
                      • 2019-04-14
                      • 2014-12-09
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      相关资源
                      最近更新 更多