Dynamic css update in Angular 2

Let's say I have an Angular2 Component

//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 file template for this component

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

And finally, the css file for this component

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

As you can see, the class has 2 properties, 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 updating the properties, width and height of the div update. What is the right way to do this?

+45
css angular
Mar 09 '16 at 4:05
source share
8 answers

try it

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

[Updated]: To install in% use

 [style.height.%]="height">Some stuff in this div</div> 
+108
Mar 09 '16 at 8:32
source share
— -

To use% instead of px or em with @Gaurav's answer, just

 <div class="home-component" [style.width.%]="80" [style.height.%]="95"> Some stuff in this div</div> 
+34
Feb 13 '17 at 1:44 on
source share

This should do it:

 <div class="home-component" [style.width]="width + 'px'" [style.height]="height + 'px'">Some stuff in this div</div> 
+13
Mar 09 '16 at 4:09
source share

Check out the 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, []); 
+6
Mar 09 '16 at 5:23
source share

You can dynamically change the style (width and height) of a div by adding a dynamic value to the inline [style.width] and the [style.hiegh] div property.

In your case, you can associate the width and height property of the HomeComponent class with the width and height property of a div inline style like this ... As pointed out by Sasxa

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

For a working demo, look at this 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
Mar 09 '16 at 6:11
source share

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 of the HomeComponent, this should affect the style attributes.

+4
Nov 25 '16 at 15:46
source share

All of the above answers are great. But if you are trying to find a solution that will not change the html files below, it is useful

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

You can import the renderer from import {Renderer} from '@angular/core';

+3
Feb 23 '17 at 11:05
source share

I liked the view of WenhaoWuI above, but I needed to identify the div with the class “.ui-tree” in the PrimeNG tree component in order to dynamically set the height. All the answers I could find required the name of the div (i.e. #treediv) to enable the use of @ViewChild (), @ViewChildren (), @ContentChild (), @ContentChilden (), etc. It was dirty with a third party component.

I finally found a snippet from Günter Zöchbauer :

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

It simplified:

 @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"); } 
0
Sep 22 '17 at 1:57 on
source share



All Articles