当用户选择一个选项时,我想用不同的颜色显示内容。例如,在下拉列表中,项目有三个选项。如果用户在“状态”占位符中选择“已确认”,则内容将以绿色显示“已确认”,而当用户选择“未确认”时,该项目将以红色显示“未确认”字样。如果用户选择“已确认并发货”,则颜色将显示为黄色。我如何使它工作?我是Angular的新手。我已经尝试了很多方法,但是没有用。
<mat-form-field>
<mat-select placeholder="Status" [formControl]="statusTypeFilter">
<mat-option value="1">Confirmed</mat-option>
<mat-option value="2">Not Confirmed</mat-option>
<mat-option value="3">Confirmed and Shipped</mat-option>
</mat-form-field>
<div class="table-container mat-elevation-z8">
<table mat-table [dataSource]="ItemConfirmationList" multiTemplateDataRows matSort matSortActive="no">
<ng-container matColumnDef="StatusName">
<th mat-header-cell *matHeaderCellDef mat-sort- header>Status</th>
<td mat-cell *matCellDef="let element">{{element.StatusName }}</td>
</ng-container>
</div>
答案 0 :(得分:0)
您应该创建3种CSS样式,每种样式用于不同的状态
CSS
.confirmed {
color: green;
}
.not-confirmed {
color: red
}
然后在模板中,使用[ngClass]
应用CSS
<td [ngClass]="{ 'confirmed': status === 'Confirmed', 'not-confirmed': status === 'Not Confirmed', 'confirm-shipped': status === 'Confirmed and Shipped' }"
mat-cell *matCellDef="let element">
{{element.StatusName}}
</td>
PS:我假设您将下拉值存储在status
变量中
答案 1 :(得分:0)
我做了几件事:
适当的 html :
<mat-form-field>
<mat-label>Status</mat-label>
<mat-select [(value)]="selected">
<mat-option *ngFor="let food of foods" [value]="food.value">
{{food.viewValue}}
</mat-option>
</mat-select>
</mat-form-field>
<!-- <p>You selected: {{selected}}</p> -->
<hr/>
<table>
<thead>
<tr>
<td> Item </td>
<td> Status </td>
</tr>
</thead>
<tbody>
<ng-container *ngFor='let pickedItem of sampleItems; let idx = index'>
<tr [ngClass]="setColor(pickedItem.status, idx)">
<td> {{pickedItem.item}}</td>
<td>
<span *ngIf='pickedItem.status == 1'> Confirmed </span>
<span *ngIf='pickedItem.status == 2'> Not Confirmed </span>
<span *ngIf='pickedItem.status == 3'> Confirmed and Shipped </span>
</td>
</tr>
</ng-container>
</tbody>
</table>
适当的 ts :
setColor(statusVal, idx){
let returnedClass:string ='defaultClass';
(statusVal == this.selected && statusVal ===1) ? returnedClass = 'confirmedClass' : 'defaultClass';
(statusVal == this.selected && statusVal ===2) ? returnedClass = 'notConfirmedClass' : 'defaultClass';
(statusVal == this.selected && statusVal ===3) ? returnedClass = 'shippedClass' : 'defaultClass';
return returnedClass;
}
适当的 css :
.confirmedClass { color:green;}
.notConfirmedClass { color:red;}
.shippedClass { color:orange;}
.defaultClass { color:#000;}