Interpolación angular usando "ngIf"

Oct 09 2020

Tengo una tabla en la que quiero que la primera columna tome un color específico según una variable de mi clase. Por ejemplo, tengo una clase DisplayProject.ts que tiene un atributo llamadoindexOfColor

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>

Quiero que la columna "el nombre del proyecto" sea verde si indexOfColor = 1y azul siindexOfColor = 2

¿Alguna solución?

Respuestas

4 DerekWang Oct 09 2020 at 02:09

Puede usar ngStyle para implementar estilos específicos basados ​​en variables.

<th [ngStyle]="{ 'background-color': indexOfColor == 1 ? 'green' : 'blue' }">
  the project name
</th>
Casaper Oct 09 2020 at 02:21

Componente:

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

Hoja de estilo SCSS:

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

Modelo:

<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>
Lud Oct 09 2020 at 09:26

Si está usando clase, puede hacer:

SCSS

.color-green {
  color: green;
}

.color-blue {
  color: blue;
}

Modelo:

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

En este caso si un día quieres agregar otra condición, solo debes agregar una línea

ZakariyaPindhariya Oct 09 2020 at 13:27
<th [style.background]="{ indexOfColor == 1 ? 'green' : {indexOfColor == 2 ? 'blue' :'black'}">
</th>

Referencia del valor de enlace al estilo