Angular2,如何将变量传递给克隆的模板

时间:2017-02-05 22:07:01

标签: angular angular2-template cloning

在Angular2中,我有一个模板代码,只要用户点击一个按钮就可以克隆,就像这里回答的那样 How to dynamically add a cloned node in angular2 (equivalent to cloneNode)

我正在尝试将变量传递给它,但它不起作用。怎么了?

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 {}

和那个笨蛋 https://plnkr.co/edit/pWeQfTLroOjKoyKnaZvL?p=preview

2 个答案:

答案 0 :(得分:3)

我已更新了您的plunkr,基本上可以在#8368找到答案:

<template #clone let-context="context">
 <div [id]="context.session">eps {{context.session}} ya</div>
</template>

this.container.createEmbeddedView(this.clone, {context: {session: session}});

答案 1 :(得分:1)

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