gpt4 book ai didi

angular - 如何将数据从条件 ng 容器传递到 ng 模板

转载 作者:行者123 更新时间:2023-12-05 02:40:41 24 4
gpt4 key购买 nike

我的数据模型:

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',
}

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

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

模板由循环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 模板中的参数。

有解决问题的办法吗?

附言

  • Angular 版本:~11.2.3
  • 似乎我对没有条件的 ngTemplateOutlet 也有同样的问题,我真的很困惑为什么这种方法不起作用(我们可以在 angular documentation 中找到类似的例子):
<ng-container *ngTemplateOutlet="icon; content: c"></ng-container>

最佳答案

使用 *ngTemplateOutlet 代替 *ngIf 的一种可能方法

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

这里表达式根据c.type决定使用哪个模板然后使用$implicit上下文

在模板中,我们可以使用 let-c

访问整个 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>

工作 Stackblitz

关于angular - 如何将数据从条件 ng 容器传递到 ng 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68420811/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com