Angular2,如何将变量传递给克隆的模板 [英] Angular2, how to pass a variable to a template that is cloned

查看:114
本文介绍了Angular2,如何将变量传递给克隆的模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Angular2中,我有一个模板代码,只要用户单击按钮,我都会在其中克隆它们,就像在这里回答
如何在angular2中动态添加一个克隆节点(等效于cloneNode)

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

还有矮子
https://plnkr.co/edit/pWeQfTLroOjKoyKnaZvL?p=preview

推荐答案

我已经更新了您的 plunkr ,基本上可以在#8368 :

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆