angular - 如何从条件 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
模板的参数。
有什么想法可以解决这个问题吗?
附言
- 角度版本:
~11.2.3
- 似乎我
ngTemplateOutlet
没有条件也有同样的问题,我真的很困惑为什么这种方法不起作用(我们可以在角度文档中找到类似的例子):
<ng-container *ngTemplateOutlet="icon; content: c"></ng-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>
工作堆栈闪电战
推荐阅读
- javascript - Laravel javascript 需要完美的滚动条
- twisted - buildbot http 服务器接口到 0.0.0.0
- jquery - 在jQuery中将多个数据附加到FormData的最有效方法
- c# - 动态数据类型 Cosmodb 和 C#
- entity-framework - 实体框架迁移上表关系不正确?
- php - 从 readfile() php 代码读取文件时,PHP/HTML 无法控制视频时间
- swift - 在尝试播放视频时打开 Optional 值时意外发现 nil
- c# - 如何使用自定义对象作为字典键?
- spring-mvc - com.fasterxml.jackson.databind.JsonMappingException:无法反序列化 org.healthinsurance.entity.MdcnData[] 的实例超出 VALUE_STRING 令牌
- dart - 变量不会在颤动中动态更改文本