Saturday, 8 October 2016

Set a style for an element in various ways using Angular2

In this post we are going to see how to set a style of an element in various ways using Angualr2



<div class="container">
    <br />

        Height : <input type="text" [(ngModel)]="height">
        Background : <input type="text" [(ngModel)]="background">
        Class : <input type="text" [(ngModel)]="classname">
        <button type="submit" [style.height.px]="height" 
                [style.background]="background" 
                [class]="classname"            
                >Submit</button>
    </div>


From the above code you can see that the height, background, class name of a button is dynamically changed using ngModel, this model value is bind to the element by [style.propertyname], for setting a pixel value we have to bind like [style.propertyname.px] , for class it should mention as [class]



Output:
**************








<br/>
    <div class="container">       
        Font Size :<label>{{fontsize}}</label>
        <input style="width:400px" type="range" [(ngModel)]="fontsize" />
        <br/>
        <button type="submit" class="btn btn-primary" 
          [ngStyle]="{'font-size':fontsize+'px'}">Dynamic Font Size</button>
    </div>


From the above code you can see the ngmodel value is bind to the element with the [ngStyle] directly

Output:
***************











<div class="container">
        <br/>
        <button type="submit" (click)="newstyle={'color':'red','background':'blue'}">
                Change Style</button>
        <button type="submit" (click)="newstyle={'height':'40px'}">
                Change Height</button>
        <button type="submit" (click)="newstyle={}">Remove Style</button> <br/><br/>        
        <input type="text" [ngStyle]="newstyle" />    
    </div>

From the above code you can see the style itself created and changed directly.

Output:
***************

















From this code you can learn how to change the style of an element in various ways using Angular2

No comments:

Post a Comment