问题
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
回答1:
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}});
回答2:
create_new_session(s : string) {
this.container.createEmbeddedView(this.clone, {context: {$implicit: session}});
}
<template #clone let-session>
<section [id]="session"
[bookmark_draggable_target]="{event_type:'moving_sessions',zone:'title_template'}"
(drop_here)="onDrop($event)">
</section>
</template>
https://angular.io/docs/ts/latest/api/core/index/ViewContainerRef-class.html#!#createEmbeddedView-anchor
来源:https://stackoverflow.com/questions/42057886/angular2-how-to-pass-a-variable-to-a-template-that-is-cloned