Angular组件中无法从app.component.css为<td>标签添加指定类名的问题求助
Angular组件中无法从app.component.css为标签添加指定类名的问题求助
嘿,我来帮你搞定这个问题!你想要给温度低于0的城市对应的<td>标签加上express类(也就是蓝色文字),但目前的代码写法有几个小问题导致样式没生效,咱们一步步来修正:
首先先梳理下你当前代码里的问题:
- 模板里的
<head>标签完全多余:Angular会自动帮你引入组件配置的CSS文件,根本不需要在app.component.html里手动加<link>,直接删掉就行。 *ngIf和<ng-template>的用法逻辑错了:你现在把*ngIf写在<td>上,会导致<td>本身的显示逻辑和内容显示混在一起,既没法正确绑定类名,还会打乱表格的结构。ngClass的正确打开方式没用到:你提到试过ngClass但没成功,应该是写法不对,咱们下面用标准写法来实现动态加类。
接下来是修正后的完整代码:
1. 修正app.component.html
删掉多余的<head>,用ngClass动态绑定类,同时用<ng-container>来处理内容显示逻辑(它不会渲染成额外DOM元素,能保持表格结构整洁):
<table> <tr> <th>City</th> <th>temp</th> </tr> <tr *ngFor="let city of cities"> <td>{{city.name}}</td> <!-- 用ngClass根据温度条件动态添加express类 --> <td [ngClass]="{'express': city.temp < 0}"> <ng-container *ngIf="city.temp < 0; else coolBlock"> {{city.temp}} (cold) </ng-container> <ng-template #coolBlock> {{city.temp}} (cool) </ng-template> </td> </tr> </table>
2. 保留app.component.css的样式(你的写法是对的)
.express { color: rgb(13, 142, 255); }
3. app.component.ts无需改动,保持原样即可
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'traning'; public cities =[{ name: 'montreal ',temp: -30 },{ name: 'toronto ', temp: 19 },{ name:'vancouver ',temp: -4 }]; }
为什么这样改能生效?
[ngClass]的逻辑:{'express': city.temp < 0}是Angular动态绑定类的标准写法——当city.temp < 0为真时,自动给<td>加上express类,反之则不添加。<ng-container>的作用:它是一个“隐形”容器,用来包裹*ngIf的内容,不会额外生成HTML元素,保证表格的结构不会被破坏。- 去掉手动引入的样式链接:Angular组件的
styleUrls配置已经让框架自动处理了样式文件的引入,手动加<link>反而可能导致样式冲突。
这样修改后,温度低于0的城市对应的温度<td>就会自动显示蓝色文字啦!
备注:内容来源于stack exchange,提问作者thgtveh7031
相关产品推荐
相关产品推荐

