Angular2, how to pass a variable to a template tha

2019-06-14 13:05发布

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

2条回答
再贱就再见
2楼-- · 2019-06-14 13:46

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}});
查看更多
做自己的国王
3楼-- · 2019-06-14 13:55
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

查看更多
登录 后发表回答