angular ng-template

解释

其实和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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值