Interpolação angular usando “ngIf”

Oct 09 2020

Tenho uma tabela em que desejo que a primeira coluna tenha uma cor específica de acordo com uma variável da minha classe. Por exemplo, eu tenho uma classe DisplayProject.ts que tem um atributo chamadoindexOfColor

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>

Eu quero que a coluna "o nome do projeto" seja verde se indexOfColor = 1e azul seindexOfColor = 2

Alguma solução?

Respostas

4 DerekWang Oct 09 2020 at 02:09

Você pode usar o ngStyle para implementar estilos específicos baseados em variáveis.

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

Folha 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

Se estiver usando uma classe, você pode fazer:

SCSS

.color-green {
  color: green;
}

.color-blue {
  color: blue;
}

Modelo:

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

Neste caso, se um dia você quiser adicionar outra condição, você só precisa adicionar uma linha

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

Referência do valor de ligação ao estilo