gpt4 book ai didi

angular - 与 <模板>

转载 作者:太空狗 更新时间:2023-10-29 16:44:48 27 4
gpt4 key购买 nike

ng-containerofficial documentation 中提到但我仍在努力了解它是如何工作的以及有哪些用例。

ngPlural 中特别提到和 ngSwitch 指令。

是否 <ng-container><template> 做同样的事情还是取决于是否编写指令以使用其中之一?

<ng-container *ngPluralCase="'=0'">there is nothing</ng-container>

<template [ngPluralCase]="'=0'">there is nothing</template>

应该是一样的吧?

我们如何选择其中之一?

如何<ng-container>在自定义指令中使用?

最佳答案

编辑:现在是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.

原答案:

根据 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.

所以这个 Angular 模板:

<div>
<ng-container>foo</ng-container>
<div>

将产生这种输出:

<div>
<!--template bindings={}-->foo
<div>

所以 ng-container当您想要在您的应用程序中有条件地附加一组元素(即使用 *ngIf="foo" )但不想用另一个元素包装它们时很有用。

<div>
<ng-container *ngIf="true">
<h2>Title</h2>
<div>Content</div>
</ng-container>
</div>

然后会产生:

<div>
<h2>Title</h2>
<div>Content</div>
</div>

关于angular - <ng-容器> 与 <模板>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39547858/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com