【问题标题】:Angular2, how to pass a variable to a template that is clonedAngular2,如何将变量传递给克隆的模板
【发布时间】:2017-06-22 19:27:06
【问题描述】:

在 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

【问题讨论】:

  • 为什么不直接将id 传递给指令的输入?
  • 我会读到它,现在我不知道该怎么做
  • 查看更多代码会很有帮助。指令是什么?实际上,您甚至可以传递元素本身,因此您不必查询它。
  • 我已经为指令添加了代码(如果有帮助的话)。
  • 你在哪里进行克隆?为什么不保留参考?你想动态改变什么值?

标签: angular angular2-template cloning


【解决方案1】:

我已经更新了你的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}});

【讨论】:

  • 谢谢!您能否详细说明为什么您的答案有效以及为什么 Günter 的答案无效?或者更重要的是,是否有任何我跳过的文档描述了这一点? (恐怕你的链接对我来说是模糊的)
  • 看起来方法 createEmbeddedView 的文档非常有限。上下文参数包含模板中可用的所有属性,您的示例可以简化为{session:session}let-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

【讨论】:

  • 那我可以改成,zone:newId} ?
  • 也可以。如果不知道代码对这些数据做了什么,我很难说出来。
  • 我把代码贴出来一点问题都没有,但是感觉这就像淹没了页面一样。我会在一分钟内添加更多。对于拖放实现,我关注了这篇文章radzen.com/blog/angular-drag-and-drop
  • 代码仍然没有显示你在哪里做createEmbeddedView。这是关于如何让 id 传递的,不是吗?
  • 现在添加了
猜你喜欢
  • 2017-11-10
  • 2016-09-26
  • 1970-01-01
  • 2018-09-04
  • 2012-08-22
  • 1970-01-01
  • 1970-01-01
  • 2019-04-03
  • 2011-05-08
相关资源
最近更新 更多