首页 > 解决方案 > 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)
  }
}

标签: angulartypescript

解决方案


CornelC 说这是不好的做法是正确的。过去我使用过响应式表单和表单数组。这里有一个答案,提供了使用表单数组设置反应式表单的详细信息:

如何在 Angular 2 中动态添加和删除表单字段

顺便说一句:你没有用结束引号关闭你的类属性,你需要用结束 ` 关闭模板字符串:

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>;`

推荐阅读