16 April 2020

NgStyle example in angular

  • Open Command prompt and use below commands to create angular project
  • E:
  • cd E:\TestProjects\Angular
  • ng new NgStyle-example-in-angular --style=scss --routing --skip-install
  • cd NgStyle-example-in-angular
  • npm install
  • Open project in visual studio code.
  • Open app.component.ts file and update code as below

  • import { Component } from '@angular/core';

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.scss']
    })
    export class AppComponent {
      Name:string;
      ngOnInit()
      {
        this.Name="jc";
      }
      getColor(number) { 
        switch (number) {
          case '1':
            return 'green';
          case '2':
            return 'blue';
          case '3':
            return 'red';
        }
      }
    }
  • Open app.component.html file and update code as below

  • <h1>NgStyle example in angular</h1>

    <div [ngStyle]="{'background-color':'green'}">
      example 1</div>
      <br/>
      <div [ngStyle]="{'background-color':Name === 'jc' ? 'red' : 'green' }">
        example 2
      </div>
      <br/>
      <div [ngStyle]="{'background-color':getColor('2')}">
        example 3
      </div>
      <br/>
      <div [style.color]="getColor('3')">example 4
      </div>

    Output:




    No comments:

    Post a Comment