Cập nhật động css trong Angular 2


108

Giả sử tôi có một Thành phần 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;
} 

Tệp html mẫu cho thành phần này

//home.component.html

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

Và cuối cùng là tệp css cho thành phần này

//home.component.css

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

Như bạn có thể thấy, có 2 thuộc tính trong lớp, widthheight. Tôi muốn các kiểu css cho chiều rộng và chiều cao khớp với các giá trị của thuộc tính chiều rộng và chiều cao và khi thuộc tính cập nhật, chiều rộng và chiều cao của bản cập nhật div. Cách thích hợp để thực hiện điều này là gì?

Câu trả lời:


264

Thử cái này

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

[Đã cập nhật]: Để đặt% sử dụng

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

50

Để sử dụng% thay vì px hoặc em với câu trả lời của @ Gaurav, chỉ cần

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

18

Điều này nên làm điều đó:

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

11

Bạn cũng có thể sử dụng hostbinding:

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

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

Bây giờ khi bạn thay đổi thuộc tính width hoặc height từ trong HomeComponent, điều này sẽ ảnh hưởng đến các thuộc tính style.


7

Câu trả lời được chấp nhận là không sai.

Đối với các kiểu được nhóm, người ta cũng có thể sử dụng chỉ thị ngStyle.

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

Các tài liệu chính thức ở đây


6

Kiểm tra Demo hoạt động tại đây

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

Nếu bạn muốn đặt động chiều rộng với biến thay vì sử dụng dấu ngoặc nhọn [] {{}}:

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

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

5

Bạn có thể tự động thay đổi kiểu (chiều rộng và chiều cao) của div bằng cách đính kèm giá trị động vào thuộc tính [style.width] và [style.hiegh] nội tuyến của div.

Trong trường hợp của bạn, bạn có thể ràng buộc thuộc tính chiều rộng và chiều cao của lớp HomeComponent với thuộc tính chiều rộng và chiều cao kiểu nội tuyến của div như thế này ... Theo chỉ dẫn của Sasxa

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

Để có bản demo hoạt động, hãy xem plunker này ( 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

Tôi thích giao diện của ý tưởng của WenhaoWuI ở trên, nhưng tôi cần xác định div với lớp .ui-tree trong thành phần cây PrimeNG để đặt chiều cao một cách linh động. Tất cả các câu trả lời tôi có thể tìm thấy yêu cầu div được đặt tên (ví dụ #treediv) để cho phép việc sử dụng @ViewChild(), @ViewChildren(), @ContentChild(), @ContentChilden()vv Điều này là lộn xộn với một thành phần của bên thứ ba.

Cuối cùng tôi đã tìm thấy một đoạn trích từ Günter Zöchbauer :

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

Điều này làm cho nó dễ dàng:

@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

Tất cả các câu trả lời trên là tuyệt vời. Nhưng nếu bạn đang cố gắng tìm một giải pháp không làm thay đổi các tệp html thì bên dưới sẽ hữu ích

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

Bạn có thể nhập trình kết xuất từ import {Renderer} from '@angular/core';


1
Vì câu trả lời này đã được đăng, Trình kết xuất không được dùng nữa. Sử dụng Renderer2 để thay thế và thay thế setElementStyle () bằng setStyle ()
Chris

2

bạn có thể đạt được điều này bằng cách gọi một hàm

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

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

0

Trong Html:

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

Trong Ts

this.maxHeightForScrollContainer = 200 //your custom maxheight
Khi sử dụng trang web của chúng tôi, bạn xác nhận rằng bạn đã đọc và hiểu Chính sách cookieChính sách bảo mật của chúng tôi.
Licensed under cc by-sa 3.0 with attribution required.