I'm new in Ionic with Angular and I have dynamic object that I want to access value on HTML img src
TS:
options = [
{
id: '0',
icon: 'assets/icons/set-comparison.svg',
text: 'Set Comparison'
},
....
];
HTML:
<li *ngFor="let item of options" [ngClass]="{ 'active' : item === selectedMenuItem }">
<button (click)="selectedMenuItem = item">
<img src="item.icon" alt="">
</button>
</li>
But when I debug it, instead get string route I get:
How can I access the property of my object correctly? Regards
CodePudding user response:
About use some like (click)="item.action"
The "events" are usually in the way (click)="myfunction()"
. If you really has a function in item.action you should write
(click)="item.action()"
But for this, you need that really the property "action" of your item was a function.
If "item" is an array of class
export class MyClass{
prop1
prop2
action(){
console.log(this.prop1 this.prop2)
}
}
You should has some like
//imagine this.service.getData return some like //[{prop1:"prop1",prop2:"prop2"},{prop1:"hello",prop2:"word"}]
this.service.getData().subscribe((res:any[]=>{ this.items=res.map(x=>{ const obj=new MyClass() Object.assign(obj,x) return obj }) })
//or this.service.getData().pipe(map((res:any[])=> res.map(x=>{ const obj=new MyClass() Object.assign(obj,x) return obj })).subscribe(res=>this.items=res)
But imagine you really received an array of object
[{prop1:"prop1",prop2:"prop2",action:"action1"},
{prop1:"hello",prop2:"word",action:action2}]
The best bet is write some like
(click)="MyFunction(item.action)"
And in your .ts you has
myFunction(action:string)
{
switch (action)
{
case "action1":
this.action1() //<--here call to a function action1 defined in .ts
break;
case "action2":
this.action2() //<--idem a function action2 defined in .ts
break;
}
But you can also make some like
this.service.getData().pipe(map((res:any[])=>
res.map(x=>({...x,action:this[x.action]})
})).subscribe(res=>this.items=res)
See that, in this case the property "action" of the first element is the function this["action1"] that we has defined in our .ts