我是Ionic with Angular的新手,我有一个动态对象,我想访问HTMLimg click
上的值
TS:
showOptions = false;
options = [
{
id: '0',
icon: 'assets/icons/set-comparison.svg',
text: 'Set Comparison',
action: 'setComparison()'
},
....
];
selectedOptionItem = this.options[0];
HTML:
<li *ngFor="let item of options" class="sidebar__content" [ngClass]="{ 'active' : item === selectedMenuItem }">
<button class="btn" (click)="selectedOptionItem = item">
<img
[attr.src]="_measures.selectedMeasure.id === 'i' ? item.icon : item.icon2"
class="sidebar__content custom__icon"
(click) ="item.action">
</button>
</li>
我以(click) ="item.action"
的身份尝试过,但它不构成动作
我创建了一个正常按钮来查看事件是否正常工作,如下所示:
<button class="nav-link btn-sm btn btn-outline" (click)="setComparison()">
Set comparison <i class="mdi mdi-compare-horizontal"></i>
</button>
是的,它工作正常,我如何才能正确访问对象的属性?问候
SetComparison组件:
async setComparison() {
const modal = await this.modalCtrl.create({
component: SetComparisonComponent,
cssClass: 'modal-comparison',
animated: true
});
modal.onDidDismiss().then((data) => {
if (data) {
}
});
return await modal.present();
}
模式控制:
constructor(
private modalCtrl: ModalController
....
)
模式控制器:
export declare class ModalController extends OverlayBaseController<ModalOptions, HTMLIonModalElement> {
private angularDelegate;
private resolver;
private injector;
constructor(angularDelegate: AngularDelegate, resolver: ComponentFactoryResolver, injector: Injector);
create(opts: ModalOptions): Promise<HTMLIonModalElement>;
static ɵfac: ɵngcc0.ɵɵFactoryDef<ModalController, never>;
static ɵprov: ɵngcc0.ɵɵInjectableDef<ModalController>;
}
当前,options
数组中项的action
属性不存储对函数的引用,而是存储函数名称的字符串,因为它位于引号之间。此外,如果要删除单引号,也会遇到问题,因为函数引用后面包含圆括号,这意味着一旦包含TypeScript文件,就会立即调用它。最后,我猜测,除非函数是全局定义的,否则将其简单地调用为setComparison
也不够,因为这并没有指定函数的上下文。如果setComparison
函数的定义范围与TypeScript代码的其余部分相同,那么用this
关键字引用它就足够了。
为了解决你的问题,你需要做两个调整:
- 在action参数中,存储对未被主动调用的函数的引用,如下所示:
action: this.setComparison
- 在单击处理程序中,主动调用对存储在
action
属性中的函数的引用,例如:(click)="item.action()"