* ng为Angular 2+中的每个项目输出不同的HTML

时间:2018-06-03 13:15:22

标签: angular frontend ngfor ng-container html-templates

我想制作通知栏并将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>

2 个答案:

答案 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>