Observablerxjs
Observablerxjs

Reputation: 722

ngFor map object

I have some difficulties to understand how the ngFor works with map.

So this is my HTML code:

<div *ngFor="let country of wars.getCountrys()">

and here my TypeScript code:

wars: Map < number, Array < country> > = new Map < number, Array < country > > ();

getCountrys() {
    console.log('getCountrys()');
    return Array.from(this.wars.keys());
}

Everything is working good, however in the console I have 2 getCountrys() I don't understand why the function getCountrys() is called 2 times.

Upvotes: 0

Views: 705

Answers (2)

Lasithe
Lasithe

Reputation: 2760

Don't use the function to generate the array. Create it inside the constructor as a variable.

In constructor:

this.countries = Array.from(this.wars.keys());

In html:

<div *ngFor="let country of countries">

Upvotes: 1

Raed Khalaf
Raed Khalaf

Reputation: 2065

in Angular, there is something called ChangeDetection its basically to detect when component data changes, and then automatically re-render the view to reflect that change.

in the Development mode in the angular application there is an additional cycle of detection is done, which means now we have two detection cycles.

these two cycles results executing your method twice.

Upvotes: 0

Related Questions