淘先锋技术网

首页 1 2 3 4 5 6 7

Angular使用NgStyle设置动态颜色

step1:Angular 中的 NgStyle 指令,您将能够为 DOM 元素设置样式属性。在NgStyle的帮助下,我们将能够轻松地设置风格。在这里,我们将为其分配对象文字

D:\vue\untitled2901\src\app\app.component.ts

import {Component, Input, OnInit} from '@angular/core';


@Component({
  selector: 'app-root',
  template: `
    <div *ngFor="let person of data">
      <span [ngStyle]="{'color':setUserColor(person.state),'font-size.px':60}">{{person.name}}</span>
    </div>
  `,
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {


  title = 'untitled2899';

  color: string = 'blue';

  data: any[] = [
    {
      "name": "Henry",
      "state": "LA"
    },
    {
      "name": "Shane",
      "state": "Chicago"
    },
    {
      "name": "AJ",
      "state": "StLouis"
    },
    {
      "name": "Parker",
      "state": "NewJersey"
    }
  ];


  @Input() header: string = 'untitled2899';


  setUserColor(state): string {
    let colorName: string;
    switch (state) {
      case 'LA':
        colorName = 'red';
        break;
      case 'Chicago':
        colorName = 'blue';
        break;
      case 'StLouis':
        colorName = 'orange';
        break;
      case 'NewJersey':
        colorName = 'green';
        break;
    }
    return colorName;
  }

  constructor() {
  }

  ngOnInit(): void {
  }


}

end