Search code examples
angulartypescriptproperty-binding

How to pass a array value as color in Angular 4


I'm new in Angular and in stackoverflow. I need to know if can I pass the value of an array in the element bidding in Angular 4.

Basically I want change the color of the #jediSign if the student are or not a jedi!

This is the template:

<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>

And this is the component:

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'
  }
 ]
}

How can I change the color from 'lightgreen' to students.color?

I put this code on github for pull requests.

Thank you!


Solution

  • Just should use style.background input:

    <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>
    

    function to get isJedi background color:

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

    By the way click should toggle isJedi? :

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