0

我是 Angular 和 stackoverflow 的新手。我需要知道是否可以在 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'
  }
 ]
}

如何将颜色从“浅绿色”更改为students.color?

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

谢谢!

4

2 回答 2

1

只需使用 ngStyle 设置颜色:

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

  <button (click)="student.isJedi = !student.isJedi">...
于 2017-10-19T21:22:43.183 回答
0

应该使用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"
于 2017-10-19T21:28:32.227 回答