Kri*_*eck 7 typescript angular
我试图找出在将元素添加到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";
}
}
Run Code Online (Sandbox Code Playgroud)
不起作用的部分是这样的:
this.html = "<button (click)='new()'>" + this.buttonText + "</button>"
Run Code Online (Sandbox Code Playgroud)
Angular 2此时不知道该怎么办(click)='new()'
.我不确定什么是正确的方法.
我期望的是能够在稍后的某些事件中向DOM添加HTML.
我没有使用Angular 1.但听起来这曾经相当于$compile
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{}
Run Code Online (Sandbox Code Playgroud)
原始答案 (由于从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";
}
}
Run Code Online (Sandbox Code Playgroud)
但重点是......如果我们只是下降到这个水平,为什么首先使用角度.我也在生产中的企业应用程序中使用Angular2.我对此功能的选择是将button
自身创建为Component,然后使用DynamicComponentLoader
to注入元素.
归档时间: |
|
查看次数: |
13972 次 |
最近记录: |