首页 >> 大全

ng-template用法

2023-09-02 大全 30 作者:考证青年

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>

结果展示

关于我们

最火推荐

小编推荐

联系我们


版权声明:本站内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 88@qq.com 举报,一经查实,本站将立刻删除。备案号:桂ICP备2021009421号
Powered By Z-BlogPHP.
复制成功
微信号:
我知道了