在 Angular 2 中动态更新 css
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35882670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamically updating css in Angular 2
提问by tt9
Let's say I have an Angular2 Component
假设我有一个 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;
}
The template html file for this component
此组件的模板 html 文件
//home.component.html
<div class="home-component">Some stuff in this div</div>
And finally the css file for this component
最后是这个组件的 css 文件
//home.component.css
.home-component{
background-color: red;
width: 50px;
height: 50px;
}
As you can see there are 2 properties in the class, width
and height
. I would like the css styles for width and height to match the values of the width and height properties and when the properties update, the width and height of the div update. What is the proper way to accomplish this?
如您所见,该类中有 2 个属性,width
并且height
. 我希望宽度和高度的 css 样式与宽度和高度属性的值相匹配,并且当属性更新时,div 的宽度和高度也会更新。完成此操作的正确方法是什么?
回答by Gaurav Mukherjee
Try this
尝试这个
<div class="home-component"
[style.width.px]="width"
[style.height.px]="height">Some stuff in this div</div>
[Updated]: To set in % use
[更新]:设置为使用百分比
[style.height.%]="height">Some stuff in this div</div>
回答by Helen
To use % instead of px or em with @Gaurav's answer, it's just
要在@Gaurav 的回答中使用 % 而不是 px 或 em,这只是
<div class="home-component" [style.width.%]="80" [style.height.%]="95">
Some stuff in this div</div>
回答by Sasxa
This should do it:
这应该这样做:
<div class="home-component"
[style.width]="width + 'px'"
[style.height]="height + 'px'">Some stuff in this div</div>
回答by 11mb
You can also use hostbinding:
您还可以使用主机绑定:
import { HostBinding } from '@angular/core';
export class HomeComponent {
@HostBinding('style.width') width: Number;
@HostBinding('style.height') height: Number;
}
Now when you change the width or height property from within the HomeComponent, this should affect the style attributes.
现在,当您从 HomeComponent 中更改宽度或高度属性时,这应该会影响样式属性。
回答by JoshuaTree
回答by Govind Samrow
If you want to set width dynamically with variable than use [] braces instead {{}}:
如果要使用变量动态设置宽度而不是使用 [] 大括号代替 {{}}:
<div [style.width.px]="[widthVal]" [style.height.px]="[heightVal]"></div>
<div [style.width.%]="[widthVal]" [style.height.%]="[heightVal]"></div>
回答by micronyks
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, []);
回答by Jorin
You can dynamically change the style(width and height) of div by attaching dynamic value to inline [style.width] and [style.hiegh] property of div.
您可以通过将动态值附加到 div 的内联 [style.width] 和 [style.hiegh] 属性来动态更改 div 的样式(宽度和高度)。
In your case you can bind width and height property of HomeComponent class with the div's inline style width and height property like this... As directed by Sasxa
在您的情况下,您可以将 HomeComponent 类的宽度和高度属性与 div 的内联样式宽度和高度属性绑定,如下所示... 按照 Sasxa 的指示
<div class="home-component"
[style.width]="width + 'px'"
[style.height]="height + 'px'">Some stuff in this div
</div>
For the working demo take a look at this plunker(http://plnkr.co/edit/cUbbo2?p=preview)
对于工作演示,请查看此 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);
}
}
回答by davaus
I liked the look of WenhaoWuI's idea above, but I needed to identify the div with class.ui-tree
in the PrimeNG tree componentto set the height dynamically.
All the answers I could find required the div to be named (ie #treediv) to enable the use of @ViewChild()
, @ViewChildren()
, @ContentChild()
, @ContentChilden()
etc. This was messy with a third party component.
我喜欢上面WenhaoWuI的想法的外观,但是我需要在PrimeNG 树组件中识别带有class的 div 以动态设置高度。所有的答案,我能找到需要被命名为格(即#treediv),允许使用的,,,等这是凌乱与第三方组件。.ui-tree
@ViewChild()
@ViewChildren()
@ContentChild()
@ContentChilden()
I finally found a snippet from Günter Z?chbauer:
我终于找到了Günter Z?chbauer 的一个片段:
ngAfterViewInit() {
this.elRef.nativeElement.querySelector('.myClass');
}
This made it easy:
这使它变得容易:
@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");
}
回答by WenhaoWu
All the above answers are great. But if you were trying to find a solution that won't change the html files below is helpful
以上所有答案都很棒。但是,如果您试图找到一种不会更改以下 html 文件的解决方案,则很有帮助
ngAfterViewChecked(){
this.renderer.setElementStyle(targetItem.nativeElement, 'height', textHeight+"px");
}
You can import renderer from import {Renderer} from '@angular/core';
您可以从 import {Renderer} from '@angular/core';