Angular中ng-template和ng-container的应用

本文详细介绍了Angular中ng-template和ng-container的使用。ng-template用于定义模板,ng-container作为逻辑容器,不生成实际DOM节点。同时,文章讨论了如何结合TemplateRef和ViewContainerRef进行动态组件创建,以及ng-container在复杂场景下的应用。

Angular的日常工作中经常会使用到ng-template和ng-container,本文对他们做一个总结。

ng-template

ng-template是一个Angular元素,它不会直接显示出来。在渲染视图之前,Angular会把它的内容替换为一个注释。ng-template是用来定义模板的,当定义好一个模板之后,可以用ng-container和ngTemplateOutlet指令来进行使用。

简单点来说,就是定义了一个模板片段,并且起了一个名字,在需要的时候可以通过名字来使用这个片段

<!--定义模板,并不会在视图中显示-->
<ng-template #loading><div class="waiting-wrap"><div class="spinner">loading...</div></div>
</ng-template>

<!--使用模板,在视图中显示-->
<ng-container *ngTemplateOutlet="loading"></ng-container> 
<ng-template #myTemp><div>Hello, Tom?</div>
</ng-template>

<div class="container"><ng-container *ngTemplateOutlet="myTemp"></ng-container><div [ngTemplateOutlet]="myTemp">Jerry</div>
</div> 

作用域的Template

带作用域的Template,可以从当前作用域获得数据。

<ng-template #userTemp let-account="name" let-age="age"><p>{
  
  {account}} - {
  
  {age}}</p>
</ng-template>

<ng-container *ngTemplateOutlet="userTemp; context: userInfo">
</ng-container>

<!--
<ng-container [ngTemplateOutlet]="userTemp" [ngTemplateOutletContext]="userInfo"></ng-container>
--> 

上面的let-account=“name”,相当于定义了一个account变量,变量的值为 context.name。也就是下面的代码:

let account = context.name;
let age = context.age; 
import { AfterViewInit, Component, ComponentFactory, ComponentFactoryResolver, ComponentRef, EventEmitter, Input, OnChanges, OnInit, Output, SimpleChanges, TemplateRef, ViewChild, ViewContainerRef } from '@angular/core';
import { MsgComponent } from '../msg/msg.component';

@Component({selector: 'app-user',templateUrl: './user.component.html',styleUrls: ['./user.c
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值