Issue
I'm new in Ionic with Angular and I have a dynamic object that I want to access value on HTML img 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>
I tried as (click) ="item.action"
but it does not make an action
I created a normal button to see if the event works correctly as:
<button class="nav-link btn-sm btn btn-outline" (click)="setComparison()">
Set comparison <i class="mdi mdi-compare-horizontal"></i>
</button>
And yes, it works correctly, how can I access the property of my object correctly? Regards
SetComparison component:
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();
}
Modal Ctrl:
constructor(
private modalCtrl: ModalController
....
)
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>;
}
Solution
Currently, the action
property in the item in the options
array does not store a reference to a function, but a string of the function name, because it's put between quotes. In addition, if you were to remove the single quotes, you would also run into problems, because the function reference includes parentheses behind it, meaning that it will get called as soon as the TypeScript file is included. Finally, I'm guessing that unless the function is globally defined, calling it as simply setComparison
won't suffice either, because this does not specify the context of the function. If the setComparison
function is defined in the same scope that the rest of your TypeScript code is, referring to it with the this
keyword should be enough.
To solve your problem, you need to make two adjustments:
- Within the action parameter, store a reference to the function that is not actively being called, as such:
action: this.setComparison
- Within the click handler, actively call the reference to the function that is stored in the
action
property, as such:(click)="item.action()"
Answered By - sjoerddt
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.