Ser*_*gii 4 parameters ng-template angular ng-container ng-content
我的数据模型:
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',
}
Run Code Online (Sandbox Code Playgroud)
迭代模型集合我需要根据其类型绘制图标。有些图标可以按通常的方式被淹没,其他图标则需要特殊的规则。所以我准备了一些templates:
<ng-template #viber>
<p>viber icon is drawn</p>
</ng-template>
Run Code Online (Sandbox Code Playgroud)
<ng-template #icon let-type="type">
<p>{{type}} icon is drawn</p>
</ng-template>
Run Code Online (Sandbox Code Playgroud)
这些模板由 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>
Run Code Online (Sandbox Code Playgroud)
在此容器声明中,我获得了正确的模板,但无法捕获传递到icon模板中的参数。
有什么想法可以解决这个问题吗?
~11.2.3ngTemplateOutlet没有条件的情况下也有同样的问题,我真的很困惑为什么这种方法不起作用(我们可以在角度文档中找到类似的示例):<ng-container *ngTemplateOutlet="icon; content: c"></ng-container>
Run Code Online (Sandbox Code Playgroud)
一种可能的方法是*ngTemplateOutlet使用*ngIf
<ng-container *ngTemplateOutlet="c.type==='viber' ? viber : icon; context: { $implicit: c }">
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
工作堆栈闪电战