Search code examples
angularangular-ng-if

Component doesn't get destroyed when *ngIf is false


I have a component with the following child component:

<app-fullscreen *ngIf="displayFullscreen" [images]="images" [selected]="selected" 
(fullscreenChange)="closeFullscreen($event)"></app-fullscreen>

When someone clicks on one of my images, this methods gets called:

openFullscreen(images: any, img: any) {
 this.images = images;
 this.selected = img;
 this.displayFullscreen = true;
}

Now the component is displayed. Once displayFullscreen is set to false again, the app-fullscreen component does not get destroyed. I noticed this in the DOM:

enter image description here

So it detects that the ngIf is now false, but it does not do anything about it. How do I make the component disappear?

Edit: Information about how I'm setting displayFullscreen to false.

In the app-fullscreen child component, I emit an event with the value "false":

closeFullscreen(){
  this.fullscreenChange.emit("false");
}

When the event is emitted, the parent component calls this method:

closeFullscreen(event: any){
  this.displayFullscreen = event;
  this.cd.detectChanges();
}

As you can see I even tried calling detectChanges() but that did not help.


Solution

  • You emit the string "false". The string "false" is truthy. So the ngIf still displays the component.

    Use booleans for boolean values, not strings.