Angular ngTemplateOutlet元素的学习笔记

150 阅读1分钟

*ngTemplateOutlet is used for two scenarios — to insert a common template in various sections of a view irrespective of loops or condition and to make a highly configured component.

将同一个template插入到一个视图不同的sections中。

例如,将id为compantLogoTemplate的模板,插入到同一个视图的不同位置去。也就是说,ngTemplateOutlet的值是模板id.

ngTemplateOutlet也可以接收一些上下文参数:

这里ngTemplateOutlet传入的值不再是硬编码的模板id,而是Component属性headerTemplate, bodyTemplate和footerTemplate.

这些值需要消费者传入,因此在Component里定义时,需要加上@Input的注解。

最后的消费代码:

Angular ngTemplateOutlet和ng-content的区别

参考文献:Everything you need to know about ng-template, ng-content, ng-container, and *ngTemplateOutlet in Angular

二者都能帮助Angular开发者实现高度可定制化的Component.

ng-content只是简单地将消费者传入的内容进行显示。无法使用ng-content进行形如ngTemplateOutlet那样的条件渲染。

You have to show the content that is received from the parent with no means to make decisions based on the content.

更多Jerry的原创文章,尽在:“汪子熙”: