我想制作通知栏并将HTML模板设为:
<ul>
<li *ngFor="let notification of notifications">
<div class="message"> ... </div>
</li>
</ul>
但是对于不同的通知,应该有不同的message
模板,例如:
<div class="message"> <b>NEW</b> message arrived </div> or
<div class="message"> Message is <b>DELETED</b> </div> or
<div class="message"> Your message is <b>SENT</b> </div> etc...
我可以在组件中创建一个丑陋的方法来打印带有这些HTML标记的消息,但是有更优雅的方法吗?
丑陋的方法:
resolveMessage(status) {
if (status == 'new') {
return '<b>NEW</b> message arrived';
} else if (status == 'sent') {
return 'Your message is <b>SENT</b>';
}
}
<div class="message"> {{ resolveMessage(notification.status) }} </div>
答案 0 :(得分:2)
<强> components.ts 强>
messages = {
new: `<b>NEW</b> message arrived`,
sent: `Your message is <b>SENT</b>`,
deleted: `Message is <b>DELETED</b>`
}
<强> template.html 强>
<li *ngFor="let notification of notifications">
<div class="message" [innerHTML]="messages[notification.status]"></div>
</li>
<强> Ng-run Example 强>
答案 1 :(得分:1)
您可以根据状态显示消息 *ngIf
<li *ngFor="let notification of notifications">
<div *ngIf="notification.status ==='new'" class="message"> NEW message arrived</div>
</li>