ng中的ng-content ng-template ng-container

在angular中,有这样三个自带的标签,但是在angular的文档中没有说明,只有在api中有简单的描述,摸索了半天才搞懂是咋回事。

ng-content

<div>
  <ng-content select=".header">

  </ng-content>
  <hr/>
  <ng-content select=".footer">

  </ng-content>
</div>

ng-content有一个select的属性,可以选择对应的嵌入标签的属性,.header的意思就是选中class=header的标签填充到当前的位置

<app-contentdemo>
  <div class="header">
    header
  </div>
  <div class="footer">
    footer
  </div>
</app-contentdemo>

一般的布局类的组件,都是使用ng-content实现,比如ng-zorror的layout组件,都可以使用ng-content实现

ng-container

ng-container在界面上是没有任何意义的,在浏览器的审查元素中,无法看到它,container意思就是容器。只装东西,不会显示。
<ng-container>
  <h1>test</h1>
</ng-container>

ng-template

template是模板的意思,ng-template标签主要就是用来加载一个模板。

<ng-template>
  <h2>模板</h2>
</ng-template>

  但是如果是这样,在浏览器中是不会渲染。必须要使用[ngif]=ture或者ngTemplateOutlet才能让模板内容渲染出来

使用[ngif]=true

<ng-template [ngIf]="true" ]>
  <h2>模板</h2>
</ng-template>

 使用ngTemplateOutlet

<ng-container *ngTemplateOutlet="greet"></ng-container>
 <ng-template #greet><span>Hello</span></ng-template>

组件嵌套中的模板上下文

使用primeng的时候,表格组件中,会出现嵌套的ng-template,并能获取到上下文中的对象。这种是怎么做的呢?

在ngTemplateOutlet可以传递一个上下文,直接把对象传递进去的就好了

<table style=" 100%">
  <thead>
  <tr>
    <th *ngFor="let label of labellist">{{label}}</th>
  </tr>
  </thead>
  <tbody>
  <ng-container *ngFor="let item of data;let i = index">
    <tr>

      <ng-container *ngFor="let row of tableColumn">
        <td style="" align="center">
          <ng-container *ngIf="row.prop">
            <label>+</label>
            {{item[row.prop]}}
          </ng-container>
          <ng-container *ngIf="row.scope">
            <ng-container *ngTemplateOutlet="row.scope;context:{row:item}"></ng-container>
          </ng-container>
        </td>
      </ng-container>
    </tr>
  </ng-container>
  </tbody>
</table>

使用

<app-apptable [data]="data">
  <app-app-col label="用户名" prop="username"></app-app-col>
  <app-app-col label="密码" prop="pwd"></app-app-col>
  <app-app-col label="昵称" prop="pwd"></app-app-col>
  <app-app-col label="测试" scope="scope">
    <ng-template #scope let-data="row">
      <span style="color: red">00-{{data.username}}</span>
    </ng-template>
  </app-app-col>
</app-apptable>

在ng-teamplate中 #scope是当前的模板的名字引用,let-xxxx是定义当前的作用域内的用于接受上下文对象的属性,

然后在在模板的作用域类,就可以使用let-xxx的xxx去点出ngTemplateOutlet的context传递的对象。

以上差不多就是我对着三个标签的理解

原文地址:https://www.cnblogs.com/boxrice/p/12604367.html