njran
njran

Reputation: 11

Why is my *ngFor list being reloaded when @HostListener event fires

I have a custom directive using a HostListener to detect when the mouse enters a list element, and using HostBinding to change the background color of the element.

  @HostBinding('style.backgroundColor') backgroundColor: string;

  @HostListener('mouseenter') mouseOver(eventData: Event) {
    this.backgroundColor = this.altColor;
  }

The element on which this directive is placed, is a list of 'devices'. When a device is clicked an event is emitted to inform other components, which use the selected device to list a series of sensors belonging to the device.

  onSelect(device: Device) {
    console.log('Device Chosen -> ' + device.name);
    this.deviceService.selectedDevice.emit(device);
  }
<mat-grid-tile
    *ngFor="let sensor of selectedDevice.sensors"
    (click)="onSelect(sensor)"
    <img src={{getImage(sensor.name)}} alt="" width=50%>
    <p> {{sensor.name}} </p>
</mat-grid-tile>

The functionality works fine. However I noticed when I placed a console.log in the getImage function (used during the ngFor loop) that the function is called each time the mouse enters (or leaves) the element with directive applied. I.e., when the HostListener is triggered, the list of sensors is reloaded?

Nothing is picked up using ngOnChanges for the component. If I remove the directive, this behavior stops. The same behavior occurs when I interact with an ngx-chart and when the chart enters animations.

Upvotes: 1

Views: 202

Answers (0)

Related Questions