ngModel,在动态添加的html中单击在4号角中不起作用 [英] ngModel, click not working in angular 4 in dynamically added html

查看:190
本文介绍了ngModel,在动态添加的html中单击在4号角中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过定位ID来添加HTML.HTML正在显示,但是 ngModel 和单击不起作用.我该如何运作?

I am trying to add Html by targeting an id. Html is showing but ngModel and click are not working. How can I make it work?

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

推荐答案

如果即时创建html并通过innerHTML进行设置,则无法使用特定于角度的模板语法.所有角度模板均在构建期间进行编译.诸如(click)="...""之类的特定于角度的内容根本无法工作.

You cannot use angular specific template syntax if you create the html on the fly and set it via innerHTML. All angular templates are compiled during build time. Angular specific things like (click)="..."" will simply not work.

无论如何,正如其他人所说,在使用angular时,您不应该直接操作html.

Anyways, as others have stated you should not be manipulating your html directly when working with angular.

像这样创建您的组件:

import { Component, ElementRef, OnInit } from '@angular/core';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
    // This field will control the visibility of your section
    isDivVisible = false;
    mytext = 'add something';
    constructor(private myElement: ElementRef) { }
    ngOnInit() {
        this.isDivVisible = true;
    }
    pop() {
        alert('hello');
    }
}

我们只是想使用 isDivVisible 变量来控制div的可见性,而不是手动创建dom元素.

Instead of manually creating the dom element, we simply want to use the isDivVisible variable to control the visibility of the div.

在您的模板中执行以下操作:

In your template do something like this:

<div *ngIf="isDivVisible">
    <input type="text" [(ngModel)]="mytext">
    <button type="button" class="btn" (click)="pop()">Basic</button>
</div>

仅当将 isDivVisible 变量设置为true时,带有 * ngIf 指令的div才可见.您可以通过将 isDivVisible 设置为false来轻松地再次隐藏它.

The div with *ngIf directive will only be visible when you set the isDivVisible variable to true. You can easily hide it again by setting isDivVisible to false.

简短说明:如果您使用ngOnInit方法,则您的组件还应该实现OnInit接口.

Short note: If you use the ngOnInit method your component should also be implementing the OnInit interface.

这篇关于ngModel,在动态添加的html中单击在4号角中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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