ngStyle directive:
------------------
*this is used to apply stylesheet[mostly multiple characteristics] to a html element,the
stylesheet created with in a component class (or) stylesheet based on a condition
*syntax:
<tagname [ngStyle]="stylesheetvarname">
or
<tagname [ngStyle]="{characteristicname:cond?value1:value2,...}">
What is the Angular ngStyle Directive?
The ngStyle directive is used to set the DOM element style properties. For example, if you want to create a button with font size 20, the color red and font-weight bold, then you could do the same using the Angular ngStyle directive as shown in the below image.
.html changes<button [ngStyle]="{'color':'red', 'font-weight': 'bold', 'font-size.px':20}">Click Me </button>Output
In the above example we have hardcoded the values, now i want to apply styles dynamically. then i need to make changes as below in ts , html files.tsexport class AttributestylebindingComponent {AddButtonCSSStyles() {let CssStyles = {'color':'blue','font-weight': 'bold','font-size.px': 20};return CssStyles;}}.html<button [ngStyle]="AddButtonCSSStyles()">Click Me </button>OutputExample 2:When I click on sum--> I want one style to be appliedWhen I click on multiply-->I want one style to be applied..ts Changesexport class AttributestylebindingComponent {AddButtonCSSStyles() {let CssStyles = {'color':'blue','font-weight': 'bold','font-size.px': 20};return CssStyles;}a:number=0;b:number=0;res:number=0;//prepare stylesheetmystyle={"color":"","visibility":"hidden"};sum(){this.res=this.a+this.b;this.mystyle={"color":"green","visibility":"visible"};}mult(){this.res=this.a*this.b;this.mystyle={"color":"red","visibility":"visible"};}}html changes<button [ngStyle]="AddButtonCSSStyles()">Click Me </button><div style="font-size:x-large;margin:20px">enter a:<input type="number" [(ngModel)]="a"> <br>enter b:<input type="number" [(ngModel)]="b"> <br><input type="button" value="sum" (click)="sum()"><input type="button" value="mult" (click)="mult()"><br><h3 [ngStyle]="mystyle">result:{{res}}</h3></div>ExampleApply styles based on gender -->Male/Female.ts changesexport class AttributestylebindingComponent {students: any[] = [{Name: 'Uday', Branch: 'CSE', Gender: 'Male'},{Name: 'Abc', Branch: 'ETC', Gender: 'Male'},{Name: 'Def', Branch: 'CSE', Gender: 'Female'},{Name: 'Ghi', Branch: 'ETC', Gender: 'Female'},{Name: 'Jkl', Branch: 'CSE', Gender: 'Male'}];}.html Changes
No comments:
Post a Comment
Thank you for visiting my blog