【问题标题】:How to pass a array value as color in Angular 4如何在Angular 4中将数组值作为颜色传递
【发布时间】:2017-10-19 21:14:00
【问题描述】:

我是 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 上用于拉取请求。

谢谢!

【问题讨论】:

  • 你试过ngStyle了吗?

标签: angular typescript property-binding


【解决方案1】:

只需使用 ngStyle 设置颜色:

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

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

【讨论】:

  • 它有效。我试过这样的,但使用 [style.backgroundColor]="student.color"。这改变了 DIV 的颜色,但我需要这个改变应该通过点击来实现。
【解决方案2】:

应该使用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"

【讨论】:

  • 太棒了!这解决了我的问题。但是第一个结果&lt;div&gt; 已经显示了student.color 的背景颜色。如何显示默认颜色并通过单击更改为student.color?谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-07
  • 2018-08-20
  • 2018-02-03
  • 2021-12-05
  • 2017-10-20
  • 1970-01-01
相关资源
最近更新 更多