gpt4 book ai didi

javascript - 如何在innerHTML Angular 2中绑定(bind)点击事件/函数?

转载 作者:行者123 更新时间:2023-12-03 04:09:06 24 4
gpt4 key购买 nike

我有一个innerHTML,如下所示:

getWidgetItem(widgetId: any) {
this._widgetId = widgetId;
this.widgets = [{'name': 'Welcome'}, {'name': 'Welcome1'}, {'name': 'Welcome2'}];
this.newArray = this.widgets.map((obj) => {
let htmlText = `
<div>
<section class="page subpage dashboard dashboard-page" style="overflow-y:hidden;">
<div class="newDashbaord">
<header>
<div class="actions">
<button class="control-btn borderless close-btn">
<span #target class="icon-close action-icon" (click)="RemoveWidget(${obj})"></span>
</button>
</div>
<h1 class="table-heading">${obj.name}</h1>
</header>
<main>
</main>
</div>
</section>
</div>`;
return htmlText;
});
}

但问题是,我无法从我的跨度访问点击事件。

我有一个函数调用如下:

private RemoveWidget(widget:any) {
if (typeof widget != 'undefined' && typeof this.widgets != 'undefined'){
console.log('CALLEDe', widget);
let index: number = this.widgets.indexOf(widget);
if (index !== -1) {
this.widgets.splice(index, 1);
}
}
}

我尝试过:

ngAfterContentInit(): void {
// console.log('target called', this.elementRef.nativeElement.querySelector('span'));
this.renderer.listen(this.elementRef.nativeElement, 'click', (event) => {
console.log('event called??', event);
// this.RemoveWidget(event);
});
}

但是我从我的 templateUrl 中得到了一个跨度。无法访问我的 insideHTML 范围中的范围。我怎样才能访问它?

最佳答案

你真的应该使用 Angular 的模板引擎。

您无需尝试通过脚本添加 html,只需在直接 html 中使用 *ngFor 即可实现您想要的结果。

some-file.html

<div *ngFor="let widget of widgets">
<section class="page subpage dashboard dashboard-page" style="overflow-y:hidden;">
<div class="newDashbaord">
<header>
<div class="actions">
<button class="control-btn borderless close-btn">
<span #target class="icon-close action-icon" (click)="RemoveWidget(widget)"></span>
</button>
</div>
<h1 class="table-heading">widget.name</h1>
</header>
<main>
</main>
</div>
</section>
</div>

The NgFor directive instantiates a template once per item from an iterable. The context for each instantiated template inherits from the outer context with the given loop variable set to the current item from the iterable.

关于javascript - 如何在innerHTML Angular 2中绑定(bind)点击事件/函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44407771/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com