Interpolation angulaire avec "ngIf"
Oct 09 2020
J'ai un tableau dans lequel je veux que la première colonne prenne une couleur spécifique en fonction d'une variable de ma classe. Par exemple, j'ai une classe DisplayProject.ts qui a un attribut appelé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>
Je veux que la colonne "le nom du projet" soit verte si indexOfColor = 1et bleue siindexOfColor = 2
Des solutions?
Réponses
4 DerekWang Oct 09 2020 at 02:09
Vous pouvez utiliser ngStyle pour implémenter des styles spécifiques basés sur des variables.
<th [ngStyle]="{ 'background-color': indexOfColor == 1 ? 'green' : 'blue' }">
the project name
</th>
Casaper Oct 09 2020 at 02:21
Composant:
@Component({ selector: 'app-comp', ... })
export class DispalyProject {
@Input() public project: Project;
@Input() public indexOfColor: 1 | 2 = 1; //can be 2
}
Feuille de style SCSS:
.default-color {
color: green;
}
.blue {
color: blue;
}
Modèle:
<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 vous utilisez la classe, vous pouvez faire:
SCSS
.color-green {
color: green;
}
.color-blue {
color: blue;
}
Modèle:
<th [ngClass]="{
'color-green': indexOfColor === 1
'color-blue': indexOfColor === 2
}">
the project name
</th>
Dans ce cas si un jour vous souhaitez ajouter une autre condition, il vous suffit d'ajouter une ligne
ZakariyaPindhariya Oct 09 2020 at 13:27
<th [style.background]="{ indexOfColor == 1 ? 'green' : {indexOfColor == 2 ? 'blue' :'black'}">
</th>
Référence de la valeur de liaison au style