简体   繁体   English

Angular 2-ngModel绑定在动态添加的DOM元素中不起作用

[英]Angular 2 - ngModel binding not working in dynamically added DOM element

Consider the following piece of code 考虑以下代码

import {Component, OnInit} from 'angular2/core';
import {bootstrap, BrowserDomAdapter} from 'angular2/platform/browser';

@Component({
selector: 'app',
template: `<div id="test"></div>
<br>Current Value is: {{ name }}`
})
class App implements OnInit{
public name = "Hello World!";
constructor() {}
ngOnInit(){
    $("#test").append("<input type='text' [(ngModel)]='name'      placeholder='Enter Name' />");
}
}

bootstrap(App);

As you can see I am adding a template dynamically to the DOM and binding the name attribute to it. 如您所见,我正在向DOM动态添加一个模板,并将name属性绑定到它。 But the resulting input textbox is not binding with the name. 但是,结果输入文本框未与名称绑定。 I am newbie and I know this may not be the right way. 我是新手,我知道这可能不是正确的方法。 If so, what could be the right way to achieve this? 如果是这样,实现这一目标的正确方法是什么?

Creating HTML on-the-fly including binding isn't supported. 不支持动态创建包含绑定的HTML。

After adding the HTML you can query the element and add an event handler imperatively to get notified about changes in the input and update the value imperatively when name changes. 添加HTML之后,您可以查询元素并强制添加事件处理程序,以获取有关输入更改的通知,并在name更改时强制更新值。

If you want dynamic templateing, I would suggest to create components with the HTML you want to insert and instantiate it dynamically. 如果要动态模板化,我建议使用要插入的HTML创建组件并将其动态实例化。

This way in that component you can do your binding as you wish and hook it up with your component. 这样,您就可以在该组件中进行绑定,并将其与组件挂钩。

This can be done with DynamicComponentLoader. 这可以通过DynamicComponentLoader完成。 When you create a new component a Promise is returned and you can access the instantiated component to add parameters or hook up EventEmitters. 创建新组件时,将返回Promise,您可以访问实例化的组件以添加参数或挂接EventEmitters。

For more detail you can check my question, which was answered. 有关更多详细信息,您可以检查我的问题,已回答。 I updated my question with a working solution to which I got to. 我用一个可行的解决方案来更新我的问题。

Angular2 DynamicComponentLoader with parameters 带有参数的Angular2 DynamicComponentLoader

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM