angular – 在创建DOM后向元素添加事件
发布时间:2020-12-17 10:17:46 所属栏目:安全 来源:网络整理
导读:我试图找出在将元素添加到DOM后如何向元素添加事件. 现在,我有这样的事情: import {Component} from 'angular2/core';@Component({ selector : 'sub-child',template : 'form [innerHTML]="html"/form'})export class SubChildClass{ private html:string;
我试图找出在将元素添加到DOM后如何向元素添加事件.
现在,我有这样的事情: import {Component} from 'angular2/core'; @Component({ selector : 'sub-child',template : '<form [innerHTML]="html"></form>' }) export class SubChildClass { private html:string; private buttonText:string; constructor() { this.buttonText = 'A new button'; this.create(); } private create() { this.html = "<button (click)='new()'>" + this.buttonText + "</button>" } private new() { this.buttonText = "Text Changed"; } } 不起作用的部分是这样的: this.html = "<button (click)='new()'>" + this.buttonText + "</button>" Angular 2不知道该怎么做(click)=’new()’.我不确定什么是正确的方法. 我期望的是能够在稍后的某些事件中向DOM添加HTML. 我没有使用Angular 1.但听起来这曾经相当于$compile in Angular 1.其他一些帖子推荐使用Dynamic Content Loader这样的东西.但这似乎不是这个用例的正确答案.所以任何帮助或指导都表示赞赏.谢谢,
更新了建议
import {Component} from '@angular/core'; @Component({ selector: 'special-button-component',template: '<button type="button" (click)="changeText()">{{buttonText}}</button>' }) export class SpecialButtonComponent{ public buttonText: string = 'A New Button'; public changeText(): void{ this.buttonText = 'Text Changed'; } } @Component({ selector : 'sub-child',template : '<form><special-button-component></special-button-component></form>' }) export class SubChildClass{} 原始答案(由于从Angular 2中删除BrowserDomAdapter而不再起作用) 如果你真的想要绑定到已经注入的非模板DOM元素,那么你可以使用Angular2的一些相当无证的功能来设置一个好的“老式”方式的事件监听器 import {Component,ElementRef} from 'angular2/core'; import {BrowserDomAdapter} from 'angular2/platform/browser'; @Component({ selector : 'sub-child',template : '<form [innerHTML]="html"></form>' }) export class SubChildClass { private html:string; private buttonText:string; constructor(private elementRef: ElementRef,private domAdapter: BrowserDomAdapter) { this.buttonText = 'A new button'; this.create(); } private create() { let button = this.domAdapter.createElement('button'); button.innerHtml = this.buttonText; this.domAdapter.on(button,'click',this.new.bind(this)); this.domAdapter.appendChild(this.elementRef.nativeElement,button); } private new() { let button = this.domAdapter.querySelector(this.elementRef.nativeElement,'button'); button.innerHTML = "Text Changed"; } } 但重点是……如果我们只是下降到这个水平,为什么首先使用角度.我也在生产中的企业应用程序中使用Angular2.我对此功能的选择是将按钮本身创建为Component,然后使用DynamicComponentLoader注入元素. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |