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

一、ng-container的使用

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

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

  • 1、angular代码片段

My name is wyl.

What is you name?

  • 2、浏览器调试窗口,可以发现标签消失了,并没有起任何作用

My name is wyl.

What is you name?

  • 3、使用场景,如下,在我们需要遍历或if判断时,它可以承担一个载体的作用
  • {{ item .name}}
  • {{ item .age}}
  • {{ item .sex}}

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

二、ng-template的使用

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

    

In template, no attributes.

In ng-container, no attributes.

浏览器输出结果是:

In ng-container, no attributes.

中的内容不会显示。当在上面的模板中添加 ngIf 指令:


   

ngIf with a ng-template.

ngIf with an ng-container.

浏览器输出结果是:

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

同加上后:

Angular’s element is not a true Web Component (unlike