Reputation: 17
I have li
tag with *ngFor
<li *ngFor="let items of buttons">
<button (click)="newMap(items.id, $event)">
{{ items.name }}
</button>
</li>
So, buttons array it looks like this:
buttons = [
{name: 'Berlin', id: 'mapBerlin'},
{name: 'New York', id: 'mapNewYork'},
{name: 'Tokyo', id: 'mapTokyo'}
]
and I assign (click)
method on tag button
:
(click)="newMap(items.id, $event)"
TypeScript:
newMap($event) {
console.log($event)
}
When I click on the button number 1, I've got this message in console:
Button number 2:
etc.
How to make a function like this ?:
newMap(this.id) {
this.markers = this.id
}
I would like change this.markers
to this.id
(this.mapBerlin)
(this.mapNewYork)
etc.
Upvotes: 0
Views: 68
Reputation: 57981
Why not?
buttons = [
{name: 'Berlin', id: this.mapBerlin},
{name: 'New York', id: this.mapNewYork},
{name: 'Tokyo', id: this.mapTokyo}
]
then you received in id the whole object
Upvotes: 0
Reputation: 893
This code is OK:
newMap = (item) => {
this.markers = item.id;
}
But I have this message in console:
'mapTokyo'. Only arrays and iterables are allowed
Upvotes: 0
Reputation: 8352
There is no need to change context of the function:
You can just do this:
newMap(id, event){
this.markers = id;
}
If you are still looking to modify context this
do it like this:
<li *ngFor="let items of buttons">
<button (click)="newMap.call(items, $event)">
{{ items.name }}
</button>
</li>
And in TS
const componenContext = this;
.
.
.
newMap(event){
componenContext.markers = this.id;
}
But i wouldn't recommend this approach. It is really hacky one.
Upvotes: 0
Reputation: 13356
Try this:
<li *ngFor="let items of buttons">
<button (click)="newMap(items)">
{{ items.name }}
</button>
</li>
newMap = (item) => {
this.markers = item.id;
}
Upvotes: 0
Reputation: 23506
I'm pretty sure your code should work like that:
newMap(newId) {
this.markers = newId;
}
Just assign the passed id.
Upvotes: 0
Reputation: 161
This is fine
<li *ngFor="let items of buttons">
<button (click)="newMap(items.id, $event)">
{{ items.name }}
</button>
</li>
Your function
newMap(id, event){
this.markers = id}
Upvotes: 1