0
votes

I'm trying to understand why hovering on item in child invoke method from parent component. Here is example link

I have parent component that pass items into child component (list) like this:

<app-list [items]="getItems()"></app-list>
...
  items = [
    {
      label: 'test',
    },
    {
      label: 'foo',
    },
  ];

  getItems(): any[] {
    console.log('getItems');
    return this.items;
  }

in app-list component:

<li *ngFor="let item of items" (mouseover)="onMouseOverOption(item)" role="option">
  <span>{{ item.label }}</span>
</li>

  onMouseOverOption(item) {
    console.log("onMouseOverOption", item);
  }

And every time when I'm hovering on list item method getItems() is invoked - twice. Can someone explain this behavior to me?

Thanks

2

2 Answers

1
votes

This is because of the ngOnChanges() method. Whenever you use a function in ngFor or ngIf, this is the problem that occurs.

Its always safe and better to use a variable, because, its value doesnot change always but when you call a method, whenever you are doing (mouseover), it will get the return the items and call the same method one more time.

Easy solution for this ==> Dont call the getItems() method but directly, assign the items variable.

I changed it in the stackblitz: Please take a look:

https://stackblitz.com/edit/angular-ivy-7aupnm?embed=1&file=src/app/list/list.component.ts

The change can be seen in app.component.html.