问题描述
我想动态创建一个按钮.我使用了innerHtml来做到这一点.我可以创建按钮.但它的点击事件不起作用.请告诉我如何解决这个问题?
I want to create a button dynamically.I used innerHtml to do this.I can create button.But it's click event not working.Please tell me how to solve this?
这是我的html代码
<div [innerHTML]="answerPanelContent"></div>
这是我的打字稿代码
answerPanelContent: any;
constructor(private sanitizer: DomSanitizer){
}
ngOnInit() {
this.answerPanelContent = this.sanitizer.bypassSecurityTrustHtml(`<button type="button" class="btn btn-primary float-left"
(click)="removeAnswer()" title="Remove Answer"
aria-label="Close">
Remove</button>`);
}
removeAnswer(){
alert('clicked');
}
这是 stackblitz 网址:https://stackblitz.com/edit/angular-nka4w9一个>
Here is the stackblitz url: https://stackblitz.com/edit/angular-nka4w9
推荐答案
我强烈建议不要为此使用 [innerHTML]
.这不是为了这个目的,也不是为了角度方式".完全没有.
I strongly recommend not using [innerHTML]
for this. It is not meant for this purpose and not the "angular way" at all.
这是解决您的问题的最佳方式和角度方式".
This is the most preferable way to solve your issue and "the angular way".
component.ts
export class AppComponent {
public buttonsTexts:Array<string> = ['First button'];
public addButton(index:number):void {
this.buttonsTexts = [...this.buttonsTexts, `button ${index}`];
}
}
template.html
<button
*ngFor="let buttonText of buttonsTexts; let i = index;"
(click)="addButton(i)">{{buttonText}}</button>
如果*ngFor
由于某些我们不知道的要求而无法解决您的问题,请仅使用此选项.
Use this only if *ngFor
is not able to solve your issue because of some requirements that we don't know.
component.ts:
export class AppComponent implements AfterViewInit {
@ViewChild('inserttarget', {static: false})
public insertTarget:ElementRef; // use this if you want to insert inside a specific element in your template
constructor(
private renderer:Renderer2,
private el:ElementRef // use this if you want to insert into your template's root
) {
}
public ngAfterViewInit():void {
this.addNewButton();
}
public addNewButton():void {
const button = this.renderer.createElement('button');
const buttonText = this.renderer.createText('Click me');
this.renderer.appendChild(button, buttonText);
this.renderer.appendChild(this.insertTarget.nativeElement, button); // use this.el.nativeElement to insert into template root
this.renderer.listen(button, 'click', () => this.addNewButton());
}
}
template.ts
<p #inserttarget>
Some text
</p>
这里有一个有效的 StackBlitz.
这篇关于如何使用angular 2+中的click事件动态创建按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!