< ng-容器>与< template> [英] <ng-container> vs <template>

查看:101
本文介绍了< ng-容器>与< template>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ng-container,但没有解释它如何工作以及用例是什么.

ng-container is mentioned in Angular 2 documentation but there is no explanation how it works and what are use cases.

ngPlural ngSwitch 指令.

It is particularly mentioned in ngPlural and ngSwitch directives.

<ng-container><template>做相同的事情吗,还是取决于是否编写了使用其中一个指令的指令?

Does <ng-container> do the the same thing as <template>, or it depends whether a directive was written to use one of them?

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

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

应该一样吗?

我们如何选择其中之一?

How do we choose one of them?

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

How can <ng-container> be used in custom directive?

推荐答案

现在为

<ng-container>进行救援

Angular <ng-container>是一个分组元素,它不会干扰样式或布局,因为Angular不会将其放置在DOM中.

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

(...)

<ng-container>是Angular解析器识别的语法元素.它不是指令,组件,类或接口.它更像是JavaScript if块中的花括号:

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;
     }

没有这些花括号,JavaScript仅在您打算有条件地将它们全部作为一个块执行时才执行第一条语句. <ng-container>满足了Angular模板中的类似需求.

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.

原始答案:

根据此提取请求:

<ng-container>是一个逻辑容器,可用于对节点进行分组,但不能在DOM树中作为节点呈现.

<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>呈现为HTML注释.

<ng-container> is rendered as an HTML comment.

所以这个有角度的模板:

so this angular template :

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

将产生这种输出:

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

因此,当您想在应用程序中有条件地追加一组元素(即使用*ngIf="foo")但不想将它们与另一个元素包装在一起时,ng-container很有用. >

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>

然后将产生:

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

这篇关于&lt; ng-容器&gt;与&lt; template&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆