欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

angular之ng-container 、ng-template的使用 有大用

angular之ng-container 、ng-template的使用

tiger亮
0.398字数 589阅读 8,857

一、ng-container的使用

初次在项目中遇到这个标签时不知道它是干嘛用的,打开浏览器调试窗口并没有发现它的存在,说明它既不是一个组件,也不是一个指令,仅仅是一个特殊的tag而已。

使用(ng-container 渲染所包含的模板内容,不包含自身。)

  • 1、angular代码片段

<div>
  <ng-container>
    <p>My name is wyl.</p>
    <p>What is you name?</p>
  </ng-container>
</div>
  • 2、浏览器调试窗口,可以发现<ng-container>标签消失了,并没有起任何作用

<div>
  <p>My name is wyl.</p>
  <p>What is you name?</p>
</div>
  • 3、使用场景,如下,在我们需要遍历或if判断时,它可以承担一个载体的作用

<ul>
  <ng-container *ngFor="let item of items">
    <li>{{ item .name}}</li>
    <li>{{ item .age}}</li>
    <li>{{ item .sex}}</li>
  </ng-container>
</ul>

另外,ng中常见错误之一的for和if不能写在同一标签上(在一个宿主元素上只能应用一个结构型指令),利用ng-container标签可以在实现功能的基础上减少层级的嵌套。

二、ng-template的使用

  • ①、先来看下面一段代码

<ng-template>
    <p> In template, no attributes. </p>
</ng-template>

<ng-container>
    <p> In ng-container, no attributes. </p>
</ng-container>

浏览器输出结果是:

In ng-container, no attributes.

即 <ng-template> 中的内容不会显示。当在上面的模板中添加 ngIf 指令:

<ng-template [ngIf]="true">
   <p> ngIf with a ng-template.</p>
</ng-template>

<ng-container *ngIf="true">
   <p> ngIf with an ng-container.</p>
</ng-container>

浏览器输出结果是:

ngIf with a ng-template.
ngIf with an ng-container.
  • ②、再来看一个例子

<ul>
  <li *ngFor="let contact of contacts | async">
    <contact-card [contact]="contact"></contact-card>
  </li>
</ul>

同加上<ng-template>后:

<ul>
  <ng-template ngFor let-contact [ngForOf]="contacts | async">
    <li>
      <contact-card [contact]="contact"></contact-card>
    </li>
  </ng-template>
</ul>

Angular’s <ng-template> element is not a true Web Component (unlike <template>). It merely mirrors the concepts behind it to allow you to use <ng-template> as it’s intended in the spec. When we compile our code (JiT or AoT), we will see no <ng-template> elements outputted in the DOM. However, this doesn’t mean we can’t use things like Shadow DOM, as they are still completely possible.

三、ng-template<ng-container>的配合使用

<ng-container *ngIf="showSearchBread; else tplSearchEmpty">
     暂时搜索不到您要的数据喔
</ng-container>
<ng-template #tplSearchEmpty>
     快快开始获取吧!
</ng-template>

四、对比<ng-template><ng-container>

  • <ng-template> :使用 * 语法糖的结构指令,最终都会转换为 <ng-template> 或 <template> 模板指令,模板内的内容如果不进行处理,是不会在页面中显示的。

  • <ng-container>:是一个逻辑容器,可用于对节点进行分组,但不作为 DOM 树中的节点,它将被渲染为 HTML中的 comment 元素,它可用于避免添加额外的元素来使用结构指令。

注意:<ng-template>是angular4的标签,<template>是angular2的标签。


来自  https://www.jianshu.com/p/388461631b1d

普通分类: