ng-template用法
ng-
是一个元素,用来渲染HTML,它不会直接展示在页面上,需要通过结构型指令将内容渲染到页面中。
在我们日常开发中见到的结构型指令,如 *ngIf,ngFor 是一个微语法,解开之后会变成 标签。在介绍之前我们下看一下ngIf解开语法糖,会是怎样的一个结构
*ngIf
<div *ngIf="hero" class="name">{{hero.name}}div>
<ng-template [ngIf]="hero"><div class="name">{{hero.name}}div>
ng-template>
ng-用法
用法1
利用指令插入模板
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';@Directive({ selector: '[appUnless]' })
export class UnlessDirective {constructor(private templateRef: TemplateRef<any>,private viewContainer: ViewContainerRef) { }@Input() set appUnless(condition: boolean) {if (!condition) {// 容器内插入模板this.viewContainer.createEmbeddedView(this.templateRef);}else {// 清除容器内模板this.viewContainer.clear();}}
}
.ts
import { Component, ViewChild, OnInit } from '@angular/core';@Component({selector: 'app-root',templateUrl: './app.component.html',styleUrls: []
})
export class AppComponent {condition = true;
}
.html
<button (click)="condition = !condition">togglebutton><div *appUnless="condition">div><ng-template [appUnless]="condition"><p class="code unless">(A) <ng-template [appUnless]="condition">p>
ng-template>
用法2
使用操作DOM
import { Component, ViewContainerRef, OnInit, ViewChild, ElementRef } from '@angular/core';@Component({selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
// $implicit 使用默认值context = { $implicit: 'World', name: 'liyq' }@ViewChild('myTpl') tpl: ElementRef;constructor(private vr: ViewContainerRef) { }ngOnInit() {// 实例化一个内嵌视图,并把它插入到该容器中。this.vr.createEmbeddedView(this.tpl, { name: 'nihao' });this.vr.get(0);// this.vr.clear();}
}
.html
<ng-container *ngTemplateOutlet="myTpl; context: context">ng-container><ng-template #myTpl let-name="name"><h2>this is myTpl {{ name }}h2>
ng-template>
结果展示