zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[Angular 2] Set Values on Generated Angular 2 Templates with Template Context

AngularsetOn with Context Template VALUES templates
2023-09-14 09:00:52 时间

Angular 2 templates have a special let syntax that allows you to define and pass a context when they’re being generated.

 

We have template:

<template #template let-description="description">
    <h2>My {{description}} template</h2>
    <button>My {{description}} button</button>
</template>

And we define 'description' variable to let data to pass into.

 

import {Component, ViewChild, ViewContainerRef, ComponentFactoryResolver} from "@angular/core";
import {WidgetThree} from "../widgets/widget-three.component";
@Component({
    selector: 'home',
    template: `
<button (click)="onClick()">Create Template</button>
<div #container></div>

<template #template let-description="description">
    <h2>My {{description}} template</h2>
    <button>My {{description}} button</button>
</template>
`
})
export class HomeComponent{
    @ViewChild('container', {read:ViewContainerRef}) container;
    @ViewChild('template') template;

    constructor(){}

    onClick(){
        this.container.createEmbeddedView(this.template, {
            description: 'sweet'
        });
    }
}