Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - Is it possible to destroy component (not dynamically created)?

I am using Angular 2 google map one of our application. We are loading marker every 5 secs using Sockets. The problem is need to remove previous marker when new marker receive from socket. There is no proper documents in Angular map official site. So thought of destroy components from our app components. And we got all the child components find the following code.

import { Component, OnInit, ViewChild, ViewChildren, QueryList } from '@angular/core';
import { Socket } from 'ng2-socket-io';
import { Marker } from './google-map';
import { SebmGoogleMapMarker } from 'angular2-google-maps/core';

@Component({
  selector: 'app-google-map',
  templateUrl: './google-map.component.html',
  styleUrls: ['./google-map.component.scss'],
  providers: [SebmGoogleMapMarker]
})
export class GoogleMapComponent implements OnInit {
  public lat: number = 51.678418;
  public lng: number = 7.809007;
  public markers: Marker[] = [];
  @ViewChildren(SebmGoogleMapMarker) SebmGoogleMapMarkers: QueryList<SebmGoogleMapMarker>;
  constructor(private socket: Socket) { }

  ngOnInit() {
    this.socket.on('markers', this.setMarkers);
  }

  setMarkers = (data: Marker[]) => {
    this.removeMarkers();
    for (let marker of data) {
      var model = new Marker(marker);
      this.markers.push(model);
    }
  }

  removeMarkers() {
    if (this.SebmGoogleMapMarkers.length > 0) { 
      this.SebmGoogleMapMarkers.forEach((ele) => {
        ele.ngOnDestroy();
      });
    }
  }
}
<div class="col-lg-12">
  <sebm-google-map [latitude]="lat" [longitude]="lng">
    <sebm-google-map-marker *ngFor="let marker of markers" [latitude]="marker.latitude" [longitude]="marker.longitude">
    </sebm-google-map-marker>
  </sebm-google-map>
</div>

We got all child components but still reference are there SebmGoogleMapMarkers query list. Is there anyway to destroy component angular way?

Actually here my concern is this.SebmGoogleMapMarkers.length is increasing every 5 sec. what i am feeling is application performance will be reduce.

Solution: I made silly mistake forgot to make marker array empty before pushing.

like image 484
Kesavan R Avatar asked Nov 08 '22 22:11

Kesavan R


1 Answers

As far as I know there is no way to destroy a component that was not dynamically added. You can use *ngIf to remove a component though:

<sebm-google-map-markers *ngIf="show">

You can also create your own *ngIf variant that for example includes the logic to remove the component when not needed anymore. Creating such a structural directive is quite simple (https://angular.io/docs/ts/latest/guide/structural-directives.html)

like image 66
Günter Zöchbauer Avatar answered Nov 14 '22 20:11

Günter Zöchbauer