Angular2,如何将变量传递给克隆的模板 [英] Angular2, how to pass a variable to a template that is cloned
问题描述
在 Angular2 中,我有一个模板代码,每当用户单击按钮时我都会克隆它,就像这里回答的一样如何动态添加angular2中的一个克隆节点(相当于cloneNode)
我试图向它传递一个变量,但它不起作用.怎么了?
import {Component, NgModule, ViewChild, ViewContainerRef} from '@angular/core'从@angular/platform-browser"导入 {BrowserModule}@成分({选择器:'我的应用',模板:`<模板#clone let-session><div [id]="session">eps {{session}} ya</div>模板><div #container></div><div><button (click)="create()">你好</button>
`,})出口类应用{名称:字符串;@ViewChild('clone') 克隆:任意;@ViewChild('container', {read:ViewContainerRef}) container:any;构造函数(){this.name = 'Angular2'}创建(){让会话 = '测试';this.container.createEmbeddedView(this.clone, {context: {$implicit: session}});}}@NgModule({进口:[浏览器模块],声明:[应用程序],引导程序:[应用程序]})导出类 AppModule {}
还有那个笨蛋https://plnkr.co/edit/pWeQfTLroOjKoyKnaZvL?p=preview
我已经更新了您的 plunkr,基本上可以在 #8368 中找到答案:
<div [id]="context.session">eps {{context.session}} ya</div>模板>this.container.createEmbeddedView(this.clone, {context: {session: session}});
In Angular2 I have a template code that I am cloning whenever the user clicks a button, just like answered here How to dynamically add a cloned node in angular2 (equivalent to cloneNode)
I am trying to pass a variable to it, but it doesn't work. What's wrong?
import {Component, NgModule, ViewChild, ViewContainerRef} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
@Component({
selector: 'my-app',
template: `
<template #clone let-session>
<div [id]="session">eps {{session}} ya</div>
</template>
<div #container></div>
<div>
<button (click)="create()">Hello</button>
</div>
`,
})
export class App {
name:string;
@ViewChild('clone') clone:any;
@ViewChild('container', {read:ViewContainerRef}) container:any;
constructor() {
this.name = 'Angular2'
}
create(){
let session = 'testing';
this.container.createEmbeddedView(this.clone, {context: {$implicit: session}});
}
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}
And the plunker https://plnkr.co/edit/pWeQfTLroOjKoyKnaZvL?p=preview
I've updated your plunkr, basically answer could be found in #8368:
<template #clone let-context="context">
<div [id]="context.session">eps {{context.session}} ya</div>
</template>
this.container.createEmbeddedView(this.clone, {context: {session: session}});
这篇关于Angular2,如何将变量传递给克隆的模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!