简体   繁体   English

使用 ng-container 与模板的好处?

[英]Benefit of using ng-container vs. template?

In angular we could do:在 angular 我们可以这样做:

template: `<ng-container #c></ng-container>`

or:或者:

template: `<template #c></template>`

To create a view container that is hidden when the template is rendered.创建一个在渲染模板时隐藏的视图容器。

Is there a difference between using ng-container over the html template alternative?在 html 模板替代品上使用ng-container有区别吗? I'm guessing Angular has to have it's own template containers like ng-template or ng-container since use of the raw html template element could break non browser based runtimes, like mobile clients, etc.我猜 Angular 必须拥有自己的模板容器,如ng-templateng-container因为使用原始html模板元素可能会破坏非基于浏览器的运行时,如移动客户端等。

The <ng-container> is always rendered, but does not represent a DOM element. <ng-container>总是被渲染,但并不代表一个 DOM 元素。 It is still attached to the component's view.它仍然附加到组件的视图。

The <ng-template> will only be rendered if it is explicitly requested. <ng-template>仅在明确请求时才会呈现。

Here's a good reference on the subject:这里有一个关于这个主题的很好的参考:

http://nataliesmith.ca/blog/2018-05-01-ngtemplate-ngcontainer-ngcontent/ http://nataliesmith.ca/blog/2018-05-01-ngtemplate-ngcontainer-ngcontent/

To create a view container that is hidden when the template is rendered.创建一个在渲染模板时隐藏的视图容器。

Always use <ng-template> when possible.尽可能使用<ng-template> The <ng-container> is for grouping DOM elements together. <ng-container>用于将 DOM 元素组合在一起。 For example;例如; when you need to apply a *ngIf to many <td> elements, because you can not use a <span> around <td> .当您需要将*ngIf应用于许多<td>元素时,因为您不能在<td>周围使用<span> <td>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM