美文网首页angular
深度解析angular中的ng-template

深度解析angular中的ng-template

作者: 窗外的雪儿飞 | 来源:发表于2019-09-26 23:41 被阅读0次

    1. 引言

    我们在angular项目中经常会用到<ng-template>,但是我们是否有想过放置在里边的代码最终都去哪儿了呢?

    其实angular中的<ng-template>和HMTL中的<template>是类似的,都是作为预渲染的一个内容模版器,DOM解析器会处理里边的元素内容,以确保内容有效,但是元素的内容不会被渲染,在适当的时机,我们可以让它渲染到页面上。有关HTML的<template>介绍可以查看这里

    2. ng-template

    在@angular/core的核心库封装下,模版ng-template使用起来变得很简单。例如:

    1. 这里我们声明模版
    <ng-template #greet>
        <p>Thanks for your interest.</p>
    </ng-template>
    
    1. 在xxx.component.ts中,我们可以使用@ViewChild装饰器获取模版实例
    @ViewChild(‘greet’) greetTemplate: TemplateRef<any>;
    
    1. 怎么使用呢?我们可以创建一个占位符来将模版插入,即:ng-container
    <ng-container #placeholder></ng-container>
    
    1. 在xxx.component.ts中,我们可以使用@ViewChild装饰器获取占位符实例并通过addTemplate()方法将模版插入
    @ViewChild(‘placeholder’, {read: ViewContainerRef}) placeholderRef: ViewContainerRef;
    
    addTemplate() {
        this.placeholderRef.clear();
        this.placeholderRef.createEmbeddedView(this.greetTemplate); // 创建嵌入式视图插入模版
    }
    
    1. 我们还可以在模版中使用变量
    • html中:
    <ng-template #details let-name let-place=”place”>
        <div class=”container”>
            <div class=”row”>
                <div class=”col-md-3">
                    <div class=”border p-3">
                        <p>
                          <strong>{{name}}</strong>&nbsp;<small>{{place}}</small>
                        </p>
                    </div>
                </div>
            </div>
        </div>
    </ng-template>
    
    • ts中:
    @ViewChild(‘details’) detailsTemplate: TemplateRef<any>;
    
    this.placeholderRef.createEmbeddedView(
        this.detailsTemplate,
        { $implicit: ‘Pranesh’, place: ‘Erode’ }
    );
    

    $implicit 属性值将被分配给未初始化的参数:let-name,let-place 初始化为上下文对象中放置属性:place。

    除了在ts中通过typescript创建嵌入视图插入模版以及模版变量。我们也可以在html中通过angular提供的ngTemplateOutlet模版指令嵌入。

    <ng-container [ngTemplateOutlet]=”details” [ngTemplateOutletContext]=”{$implicit: ‘Pranesh’, place: ‘Erode’}”></ng-container>
    

    相关文章

      网友评论

        本文标题:深度解析angular中的ng-template

        本文链接:https://www.haomeiwen.com/subject/ybqouctx.html