在角度2中动态更新 css

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

236157 次浏览

这个应该可以:

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

检查工作演示这里

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

通过将动态值附加到 div 的 inline [ style.width ]和[ style.hiegh ]属性,可以动态更改 div 的样式(width 和 height)。

在您的示例中,您可以使用 div 的 inline style width and height 属性绑定 HomeComponent 类的 width 和 height 属性,如下所示..。 由萨斯克斯执导

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

试试这个

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

[更新] : 设置% use

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

还可以使用主机绑定:

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


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

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

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

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

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

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

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

我喜欢上面 文好武想法的外观,但是我需要在 < em > PrimeNG 树组件 中用 同学们 .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");
}

公认的答案并非不正确。

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

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

官方文件是 给你

如果希望使用变量动态设置宽度,请使用[]大括号代替\{\{} :

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


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

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

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


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

在 HTML 中:

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

以 T 开头

this.maxHeightForScrollContainer = 200 //your custom maxheight

我的解决方案是 @ViewChild()ngAfterViewInit()功能的结合。

HTML:

<div
class="form-field text-form-field"
#textInputContainer
>
<label *ngIf="field?.label"> My Label </label>
<input type="text"/>
</div>

TS:

  @ViewChild("textInputContainer") textInputContainer;


constructor() {}


ngOnInit(): void {}


ngAfterViewInit(): void   {
this.textInputContainer.nativeElement.style.width = "50%";
}