<ng-容器>与<模板> [英] <ng-container> vs <template>
问题描述
ng-container
在官方文档中提到a> 但我仍在努力了解它是如何工作的以及用例是什么.
是否与 做同样的事情,还是取决于是否编写了指令来使用其中之一?
是
<ng-container *ngPluralCase="'=0'">什么都没有</ng-container>
和
<template [ngPluralCase]="'=0'">什么都没有</template>
应该是一样的?
我们如何选择其中之一?
如何在自定义指令中使用
?
Edit 2 : 它不再记录!
现在它是记录
<块引用>
来救援
Angular <ng-container>
是一个分组元素,它不会干扰样式或布局,因为 Angular 不会将其放入 DOM 中.
<块引用>
(...)
<块引用>
是 Angular 解析器识别的语法元素.它不是指令、组件、类或接口.它更像是 JavaScript if-block 中的花括号:
if (someCondition) {
statement1;陈述2;陈述3;}
<块引用>
如果没有这些大括号,JavaScript 只会在您打算将所有语句作为单个块有条件地执行时才执行第一条语句.
满足了 Angular 模板中的类似需求.
原答案:
根据这个拉取请求:
<块引用>
是一个逻辑容器,可用于对节点进行分组,但不会作为节点呈现在 DOM 树中.
<块引用>
呈现为 HTML 注释.
所以这个角度模板:
<ng-container>foo</ng-container><div>会产生这种输出:
<!--template bindings={}-->foo<div>所以 ng-container
当你想在你的应用程序中有条件地附加一组元素(即使用 *ngIf=foo"
)时很有用,但 不想用另一个元素包裹它们.
<ng-container *ngIf=true"><h2>标题</h2><div>内容</div></ng-容器>
然后将产生:
<h2>标题</h2><div>内容</div>
ng-container
is mentioned in the official documentation but I'm still trying to understand how it works and what are use cases.
It is particularly mentioned in ngPlural
and ngSwitch
directives.
Does <ng-container>
do the same thing as <template>
or does it depend on whether a directive was written to use one of them?
Are
<ng-container *ngPluralCase="'=0'">there is nothing</ng-container>
and
<template [ngPluralCase]="'=0'">there is nothing</template>
supposed to be the same?
How do we choose one of them?
How can <ng-container>
be used in a custom directive?
解决方案 Edit 2 : It is NOT documented anymore !
Edit : Now it is documented
<ng-container>
to the rescue
The Angular <ng-container>
is a grouping element that doesn't interfere with styles or layout because Angular doesn't put it in the DOM.
(...)
The <ng-container>
is a syntax element recognized by the Angular parser. It's not a directive, component, class, or interface. It's more like the curly braces in a JavaScript if-block:
if (someCondition) {
statement1;
statement2;
statement3;
}
Without those braces, JavaScript would only execute the first statement when you intend to conditionally execute all of them as a single block. The <ng-container>
satisfies a similar need in Angular templates.
Original answer:
According to this pull request :
<ng-container>
is a logical container that can be used to group nodes but is not rendered in the DOM tree as a node.
<ng-container>
is rendered as an HTML comment.
so this angular template :
<div>
<ng-container>foo</ng-container>
<div>
will produce this kind of output :
<div>
<!--template bindings={}-->foo
<div>
So ng-container
is useful when you want to conditionaly append a group of elements (ie using *ngIf="foo"
) in your application but don't want to wrap them with another element.
<div>
<ng-container *ngIf="true">
<h2>Title</h2>
<div>Content</div>
</ng-container>
</div>
will then produce :
<div>
<h2>Title</h2>
<div>Content</div>
</div>
这篇关于<ng-容器>与<模板>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文