Nyan Catek
Nyan Catek

Reputation: 17

Assign another function "this" from the button inside ngFor

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

Answers (6)

Eliseo
Eliseo

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

Naturo Power
Naturo Power

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

Mario Petrovic
Mario Petrovic

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

Faly
Faly

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

Maximilian Riegler
Maximilian Riegler

Reputation: 23506

I'm pretty sure your code should work like that:

newMap(newId) {
  this.markers = newId;
}

Just assign the passed id.

Upvotes: 0

H. Hakvoort
H. Hakvoort

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

Related Questions