I've two arrays:
names = ['asdf', 'eli', 'neo', 'rashi'];
fullName = [];
doMap() {
this.names.map((name) => {
let nn = name.concat(' qwerty').toUpperCase();
this.fullName.push(nn);
});
}
And in .html file i'm calling the array using string interpolation & looping it through ngFor directive:
{{ doMap() }}
<div *ngFor="let name of fullName; let i = index">
{{ i + 1 }} {{ name }}
</div>
but o/p is showing this:
1 ASDF QWERTY
2 ELI QWERTY
3 NEO QWERTY
4 RASHI QWERTY
5 ASDF QWERTY
6 ELI QWERTY
7 NEO QWERTY
8 RASHI QWERTY
9 ASDF QWERTY
10 ELI QWERTY
11 NEO QWERTY
12 RASHI QWERTY
My question is why it's get repeting three times instead of one?
Because you are pushing new items into the fullName
array each time the doMap()
function runs and it runs more than once because of the change detection cycles triggered by Angular. What you probably want is to always create one and the same array instead of mutating the existing one and adding new entries to it.
doMap() {
return this.names.map((name) => {
return name.concat(' qwerty').toUpperCase();
});
}
<div *ngFor="let name of doMap(); let i = index">
{{ i + 1 }} {{ name }}
</div>