Show pageBacklinksBack to top This page is read only. You can view the source, but not change it. Ask your administrator if you think this is wrong. ====== Directive ngStyle ====== Assume we have a component called servers. By clicking the button, the font size of the text will increase, and the background color of it will change. {{ :ng:ng_style.png?nolink&400 |}} ===== servers.component.html ===== Here we user **binding** for our ngStyle directive. The value of each CSS attribute can be an expression. Here is an example, we can see that the attributes are mapped to functions getFontSize(), and getRandomColor(). <code> <p [ngStyle]="{fontSize: getFontSize()+'em', background:getRandomColor()}"> The button is clicked </p> <button (click)="onButtonClicked()">Increase font size</button> </code> ===== servers.component.ts ===== Here is code, similar to the ngIf example. <code> import {Component, OnInit} from '@angular/core'; @Component({ selector: 'app-servers', templateUrl: './servers.component.html', styleUrls: ['./servers.component.css'] }) export class ServersComponent implements OnInit { iFontSize: number; //in em constructor() { } ngOnInit() { this.iFontSize = 1; } onButtonClicked() { this.iFontSize = this.iFontSize + 0.25; } getFontSize() { return this.iFontSize; } getRandomColor() { let i, j: number; let s: string; s = ""; for (j = 0; j < 6; j++) { i = Math.round(Math.random() * 15); switch (i){ case 10: s+="a";break; case 11: s+="b";break; case 12: s+="c";break; case 13: s+="e";break; case 14: s+="e";break; case 15: s+="f";break; default: s += i } } return "#" + s; } } </code> ng/directive_ngstyle.txt Last modified: 2019/11/18 17:01by chongtin