typescript 在创建 DOM 后向元素添加事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35210072/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add events to elements after the DOM has been created
提问by Kris Hollenbeck
I am trying to figure out how I can add events to an element after it has been added to the DOM.
我想弄清楚如何在将事件添加到 DOM 后向元素添加事件。
Right now, I have something like this:
现在,我有这样的事情:
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";
}
}
The part that doesn't work is this:
不起作用的部分是这样的:
this.html = "<button (click)='new()'>" + this.buttonText + "</button>"
Angular 2 doesn't know what to do with (click)='new()'
at this point. I am not really sure what is the right way to do this.
此时 Angular 2 不知道如何处理(click)='new()'
。我不确定这样做的正确方法是什么。
What I would expect is to be able to add HTML to the DOM at a later point with some corresponding events.
我希望能够在稍后使用一些相应的事件将 HTML 添加到 DOM。
I haven't worked with Angular 1. But it sounds like this used to be the equivalent of $compile
in Angular 1. Some other post recommend using Dynamic Content Loaderfor stuff like this. But that doesn't seem like the right answer for this use case. So any help or guidance is appreciated. Thanks,
我没有使用过 Angular 1。但听起来这曾经相当于$compile
Angular 1。其他一些帖子推荐使用动态内容加载器来处理这样的事情。但这似乎不是这个用例的正确答案。因此,任何帮助或指导表示赞赏。谢谢,
回答by SnareChops
Updated Suggestion
更新建议
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{}
Original Answer(Does not work anymore due to the removal of BrowserDomAdapter from Angular 2)
原始答案(由于从 Angular 2 中删除了 BrowserDomAdapter,因此不再有效)
If you reallywant to bind to a non-template DOM element that has been injected then you can set up an event listener the good 'ol fashioned way using some rather undocumented features of Angular2
如果您真的想绑定到已注入的非模板 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";
}
}
But what's the point... why use angular in the first place if we just drop down to this level. I also am using Angular2 in an Enterprise Application in production. And my choice for this functionality would be to create the button
itself as a Component, and then use the DynamicComponentLoader
to inject the element in.
但是有什么意义......如果我们只是下降到这个级别,为什么首先使用 angular 。我还在生产中的企业应用程序中使用 Angular2。我对这个功能的选择是将其button
自身创建为一个组件,然后使用DynamicComponentLoader
将元素注入其中。
回答by Truc
I use ngFor to repeat DOM. When you press click button, add item to array. Example: + Component:
我使用 ngFor 来重复 DOM。当您按下单击按钮时,将项目添加到数组中。示例: + 组件:
export class AbcComponent {
billingInforArr: RegisterBillingInfoModel[] = [];
months: any[] = [];
years: any[] = [];
constructor(private fb: FormBuilder, private router: Router) {
for (let i = 1; i <= 12; i++) {
this.months.push({ value: i, text: i });
}
let today = new Date();
let year = today.getFullYear();
for (let i = 1; i <= 10; i++) {
this.years.push({ value: year + i, text: year + i });
}
if (localStorage.getItem('listCard') != null) {
this.billingInforArr = JSON.parse(localStorage.getItem('listCard'));
}
}
addCard(value: any) {
this.billingInforArr.push({ Id: Date.now().toString(), NameOnCard: value.name, CardNumber: value.cardNumber, ExpMonth: value.expMonth, ExpYear: value.expYear, Expire: `${value.expMonth}/${value.expYear}` });
localStorage.setItem('listCard', JSON.stringify(this.billingInforArr));
}
removeCard(value: any) {
console.log(value);
console.log(this.billingInforArr);
}
}
- HTML:
- HTML:
<div class="form-group list-credit" *ngFor="let item of billingInforArr">
<div class="content-credit">
<i class="material-icons remove" (click)="removeCard(item.Id)">cancel</i>
</div>
</div>