Angular 7中如何根据条件设置元素属性值?
解决Angular中动态设置
data-color和FontAwesome图标显示问题 这两个问题都可以通过Angular的属性绑定特性轻松解决,我给你分步拆解实现方案:
1. 动态设置data-color属性
你可以通过组件方法或对象映射两种方式,根据notification_type返回对应的颜色值,再用Angular的属性绑定语法绑定到data-color上。
方法一:使用组件方法(逻辑清晰)
在组件类里定义一个方法,接收notification_type参数并返回对应颜色:
// 组件.ts文件 getNotificationColor(type: number): string { switch(type) { case 1: return 'green'; case 2: return 'red'; case 3: return 'yellow'; default: return 'gray'; // 设置默认值,避免未匹配类型时出错 } }
然后在模板中用属性绑定语法(注意attr.前缀,因为data-color是自定义属性):
<li class="feed-item" *ngFor="let notification of Notificationslist" [attr.data-color]="getNotificationColor(notification.notification_type)"> {{ notification.notification }} </li>
方法二:使用对象映射(更简洁高效)
如果后续要扩展更多类型,用对象映射会更易维护,也避免多次调用函数:
// 组件.ts文件 notificationStyles = { 1: { color: 'green' }, 2: { color: 'red' }, 3: { color: 'yellow' } };
模板中直接通过索引访问,搭配可选链运算符防止类型未匹配时出错:
<li class="feed-item" *ngFor="let notification of Notificationslist" [attr.data-color]="notificationStyles[notification.notification_type]?.color || 'gray'"> {{ notification.notification }} </li>
2. 解决FontAwesome Unicode显示为字符串的问题
你之前遇到的核心问题是:返回的被当成纯文本,而非解析为Unicode字符。这是因为HTML实体在属性绑定中不会被自动解析,正确做法是使用JavaScript Unicode转义字符(而非HTML实体)。
实现步骤
同样用方法或对象映射返回对应的Unicode转义值:
// 组件.ts文件 getNotificationIcon(type: number): string { switch(type) { case 1: return '\uf00c'; // 对应FontAwesome的check图标(原HTML实体) case 2: return '\uf00d'; // 对应close图标(),可按需替换 case 3: return '\uf0e7'; // 对应bell图标(),可按需替换 default: return '\uf128'; // 默认图标 } }
然后绑定到data-content属性:
<li class="feed-item" *ngFor="let notification of Notificationslist" [attr.data-content]="getNotificationIcon(notification.notification_type)" [attr.data-color]="getNotificationColor(notification.notification_type)"> {{ notification.notification }} </li>
为什么这样能解决?
'\uf00c'是JavaScript的Unicode转义语法,会被直接转换成对应字符,FontAwesome的伪元素(比如:before)读取data-content属性时,就能识别这个字符并渲染成图标;而是HTML实体,在属性绑定中会被作为纯文本处理,所以只会显示字符串本身。
整合后的完整代码示例
组件类
import { Component } from '@angular/core'; @Component({ selector: 'app-notifications', templateUrl: './notifications.component.html' }) export class NotificationsComponent { Notificationslist = [ { notification: "Example Notification", notification_type: 1 }, { notification: "Example Notification 2", notification_type: 2 }, { notification: "Example Notification 3", notification_type: 3 } ]; getNotificationColor(type: number): string { switch(type) { case 1: return 'green'; case 2: return 'red'; case 3: return 'yellow'; default: return 'gray'; } } getNotificationIcon(type: number): string { switch(type) { case 1: return '\uf00c'; case 2: return '\uf00d'; case 3: return '\uf0e7'; default: return '\uf128'; } } }
模板
<ul> <li class="feed-item" *ngFor="let notification of Notificationslist" [attr.data-content]="getNotificationIcon(notification.notification_type)" [attr.data-color]="getNotificationColor(notification.notification_type)"> {{ notification.notification }} </li> </ul>
内容的提问来源于stack exchange,提问作者Namitha
相关产品推荐
相关产品推荐

