如何在 Angular 4 中将数组值作为颜色传递

How to pass a array value as color in Angular 4

我是 Angular 和 Whosebug 的新手。我需要知道是否可以在 Angular 中的元素投标中传递数组的值 4.

基本上,如果学生是不是绝地武士,我想改变#jediSign 的颜色!

这是模板:

<div *ngIf="student">
  Student: <a href="#" (click)="clicked()">{{student?.name}}</a>
  <br/>
  <div *ngIf="student?.isJedi">
  Jedi Temple: {{student?.temple}} <br/>
  </div>
  <div #jediSign class="jediSign"></div>
  <button (click)="jediSign.style.background='lightgreen'">Is Jedi?
  </button>
 </div>

这是组件:

export class AppComponent {

 students: Student[] = [
  {
   name: 'Luke', 
   isJedi: true, 
   temple: 'Coruscant', 
   color: 'lightgreen'
   },
  {
   name: 'Leia', 
   isJedi: false, 
   color: 'red'
   },
  {
   name: 'Han Solo', 
   isJedi: false, 
   color: 'red'
  }
 ]
}

如何将颜色从 'lightgreen' 更改为 students.color?

我将此代码放在 github 上用于拉取请求。

谢谢!

只需使用 ngStyle 设置颜色即可:

<div ... [ngStyle]="{'background-color': student.isJedi ?
 student.color : 'lightgrey'}"..>

  <button (click)="student.isJedi = !student.isJedi">...

只是应该使用 style.background 输入:

<div *ngIf="student">
  Student: <a href="#" (click)="clicked()">{{student?.name}}</a>
  <br/>
  <div *ngIf="student?.isJedi">
  Jedi Temple: {{student?.temple}} <br/>
  </div>
  <div #jediSign class="jediSign" [style.background]="isJediBackgroundColor(student)" ></div>
  <button (click)="student.isJedi = !student.isJedi">Is Jedi?
  </button>
 </div>

获取isJedi背景颜色的函数:

isJediBackgroundColor(student) {
  return student.isJedi ? student.color : '';
}

顺便说一下 click 应该切换 isJedi 吗? :

(click)="student.isJedi = !student.isJedi"