前端笔记我的angular学习我爱编程

angular之ng-container 、ng-templat

2018-01-12  本文已影响0人  w_tiger

一、ng-container的使用

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

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

<div>
  <ng-container>
    <p>My name is wyl.</p>
    <p>What is you name?</p>
  </ng-container>
</div>
<div>
  <p>My name is wyl.</p>
  <p>What is you name?</p>
</div>
<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>是angular4的标签,<template>是angular2的标签。

上一篇 下一篇

猜你喜欢

热点阅读