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.

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().

<p [ngStyle]="{fontSize: getFontSize()+'em', background:getRandomColor()}">
  The button is clicked
</p>
<button (click)="onButtonClicked()">Increase font size</button>

Here is code, similar to the ngIf example.

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;
  }
}
  • ng/directive_ngstyle.txt
  • Last modified: 2019/11/18 17:01
  • by chongtin