firas1
firas1

Reputation: 169

Angular interpolation using "ngIf"

I have a table in which I want the first column to take a specific color according to a variable in my class. For example, I have a class DisplayProject.ts which has an attribute called indexOfColor

DisplayProject.ts

export class DispalyProject implements OnInit {
  ngOnInit(): void {
  }

  project: Project;
  indexOfColor: number = 1; // can be 2 

  constructor () {
  }
}

DisplayProject.html

<table>
  <thead>
    <tr>
      <th>the project name</th>
      <th>the project date</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>project.name</td>
      <td>project.date</td>
    </tr>
  </tbody>
</table>

I want the column "the project name" to be green if indexOfColor = 1 and be blue if indexOfColor = 2

Any solutions ?

Upvotes: 2

Views: 202

Answers (4)

Zakariya Pindhariya
Zakariya Pindhariya

Reputation: 66

<th [style.background]="{ indexOfColor == 1 ? 'green' : {indexOfColor == 2 ? 'blue' :'black'}">
</th>

Reference from Binding value to style

Upvotes: 0

Lud
Lud

Reputation: 296

If you're using class you can do:

SCSS

.color-green {
  color: green;
}

.color-blue {
  color: blue;
}

Template:

<th [ngClass]="{
    'color-green': indexOfColor === 1
    'color-blue': indexOfColor === 2
    }">
    the project name
</th>

In this case if one day you want to add another condition, you just have to add one line

Upvotes: 0

Casaper
Casaper

Reputation: 116

Component:

@Component({ selector: 'app-comp', ... })
export class DispalyProject {
  @Input() public project: Project;
  @Input() public indexOfColor: 1 | 2 = 1; //can be 2
}

SCSS stylesheet:

.default-color {
  color: green;
}
.blue {
  color: blue;
}

Template:

<table>
  <thead>
    <tr>
     <th class="default-color" [ngClass]="{ blue: indexOfColor === 2 }">
       the project name
     </th>
     <th>
       the project date
     </th>
    </tr>
  </thead>
  <tbody>
   <tr>
     <td>project.name</td>
     <td>project.date</td>
   </tr>
  </tbody>
</table>

Upvotes: 0

Derek Wang
Derek Wang

Reputation: 10194

You can use ngStyle to implement specific styles based on variables.

<th [ngStyle]="{ 'background-color': indexOfColor == 1 ? 'green' : 'blue' }">
  the project name
</th>

Upvotes: 4

Related Questions