首页 > 解决方案 > 如何从条件 ng-container 将数据传递给 ng-template

问题描述

我的数据模型:

export class Contact {
  constructor(
    public type: ContactTypes,
    public name: string,
    public link?: string
  ) {
  }
}
export enum ContactTypes {
  Address = 'address-card-o',
  Phone = 'phone',
  Mobile = 'mobile',
  Email = 'envelope-o',
  FaceBook = 'facebook',
  Viber = 'viber',
  Instagram = 'instagram',
  Skype = 'skype',
  Linkedin = 'linkedin',
  VK = 'vk',
  Youtube = 'youtube-play',
  Messanger = 'messanger',
}

迭代模型集合我需要根据它们的类型绘制图标。一些图标可以以通常的方式被淹没,而另一些则需要特殊的规则。所以我准备了一些templates

<ng-template #viber>
    <p>viber icon is drawn</p>
</ng-template>
<ng-template #icon let-type="type">
    <p>{{type}} icon is drawn</p>
</ng-template>

模板由 looped 使用ng-container

<div class="cell" *ngFor="let c of $contacts | async">
    <a href="#">
        <ng-container *ngIf="c.type==='viber'; then viber; else icon; context: c">
        </ng-container>
        {{ c.name }}
    </a>
</div>

问题

在这个容器声明中,我得到了正确的模板,但我无法捕获传递给icon模板的参数。

有什么想法可以解决这个问题吗?

附言

<ng-container *ngTemplateOutlet="icon; content: c"></ng-container>

标签: angularparametersng-templateng-contentng-container

解决方案


一种可能的方式来使用*ngTemplateOutlet而不是*ngIf

   <ng-container *ngTemplateOutlet="c.type==='viber' ? viber : icon; context: { $implicit: c }">

这里的表达式决定使用哪个模板,c.type然后使用带有 $implicit 的上下文

在模板中我们可以访问整个c对象let-c

<ng-template #viber let-c>
  <p>viber icon is drawn {{c.desc}}</p>
</ng-template>

<ng-template #icon let-c>
  <p>{{c.type}} icon is drawn</p>
</ng-template>

工作堆栈闪电战


推荐阅读