angular - ngModel,单击在动态添加的 html 中无法以 Angular 4 工作
问题描述
我正在尝试通过定位 id 来添加 Html。Html 正在显示,但ngModel
单击不起作用。我怎样才能让它工作?
app.component.html
<div id="myid">
</div>
app.component.ts
import { Component, ElementRef } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
mytext = "add something"
constructor(private myElement: ElementRef) {}
ngOnInit() {
this.addDiv()
}
pop(){
alert("hello")
}
addDiv(){
var div = document.createElement('div');
div.innerHTML = `<div>
<input type="text" [(ngModel)]="mytext">
<button type="button" class="btn (click)="pop()">Basic</button>
</div>`;
this.myElement.nativeElement.querySelector('#myid').append(div)
}
}
解决方案
CornelC 说这是不好的做法是正确的。过去我使用过响应式表单和表单数组。这里有一个答案,提供了使用表单数组设置反应式表单的详细信息:
顺便说一句:你没有用结束引号关闭你的类属性,你需要用结束 ` 关闭模板字符串:
div.innerHTML = `<div>
<input type="text" [(ngModel)]="mytext">
<button type="button" class="btn (click)="pop()">Basic</button>
</div>;
改成:
div.innerHTML = `<div>
<input type="text" [(ngModel)]="mytext">
<button type="button" class="btn" (click)="pop()">Basic</button>
</div>;`
推荐阅读
- java - 正则表达式用嵌套括号分割java中的字符串
- kubernetes - 在Helm 中覆盖子图的值
- kubernetes - Ingress 可以根据 ip 路由请求吗?
- javascript - 代码战争 Persistent Bugger 问题与 if 语句未运行 for-loop
- android - 改造中的 CompositeException
- reactjs - 模拟在反应js中没有状态就无法工作
- vue.js - 监听 Vue 中所有子组件发出的事件
- matlab - 在 MATLAB 中执行 FFT 后的高频杂散
- oracle - 如何使用 SqL ldr 将大小超过 4000 字节的字符串插入 CLOB 类型的表列
- javascript - 如何访问javascript中的每个索引?