angular ng-template

本文深入探讨了Angular中模板引用变量的使用方法,包括@ViewChild装饰器的应用,以及如何通过ViewContainerRef显示模板内容。同时,文章解释了*ngFor和*ngIf背后的实现原理,揭示了它们如何利用模板来提高代码的简洁性和可读性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

解释

其实和html5的template是一样的就是将模板保存到html中然后需要时再抓出来显示到指定位置

代码

import { Component, ViewChild, TemplateRef,ViewContainerRef } from '@angular/core';

@Component({
  selector: 'app-root',
  // templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  template: `
    <div>
      <ng-template #tpl>
        <span>鬼子到我想干什么</span>
      </ng-template>
      <div #container></div>
      <button (click)="showTpl()">btn</button>
    </div>
  `
})
export class AppComponent {
  title = 'try-tpl';
  @ViewChild('tpl') tt: TemplateRef<void>;
  @ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;
  showTpl() {
    this.container.createEmbeddedView(this.tt);
  }
}

在这里插入图片描述
当然其实也可以

import { Component, ViewChild, TemplateRef,ViewContainerRef } from '@angular/core';

@Component({
  selector: 'app-root',
  // templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  template: `
    <div>
      <ng-template #tpl>
        <span>鬼子到我想干什么</span>
      </ng-template>
      <div #container></div>
      <button (click)="showTpl()">btn</button>
    </div>
  `
})
export class AppComponent {
  title = 'try-tpl';
  @ViewChild('tpl') tt: TemplateRef<void>;
  @ViewChild('tpl', { read: ViewContainerRef }) container: ViewContainerRef;
  showTpl() {
    this.container.createEmbeddedView(this.tt);
  }
}

效果是一样的
viewContainerRef 获取到的就是一个容器

拓展

ngFor和ngIf其实就是用的,没有这个标签的原因是*这语法糖

<div *ngFor="let hero of heroes;">
 {{hero.name}}
</div>

解析成

<ng-template ngFor let-hero [ngForOf]="heroes" >
 <div>{{hero.name}}</div>
</ng-template>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值