Toggling the visibility of a component with an Input function in Angular

Viewed 32

I have a component that accepts a callback function @Input() closeCallback: () => void;

and calls it in a close function like this :

  close() {
    this.closeCallback();
  }
<button class="close" (click)="close()">
        <img src="assets/img/share/icon_close_dark.svg" />
    </button>

So in the parent component I passed a function to it :

<ng-container  *ngIf="isPopupOpen">
<e2-fullscreen-popup
  [title]="'top promotions'"
  [closeCallback]="closePopup"
  >
...
</e2-fullscreen-popup>
</ng-container>
  closePopup() {
   
    this.isPopupOpen = false;
    console.log('this.isPopupOpen',this.isPopupOpen);
  }

so why I'm not able to remove the component when clicking on the button, even thou the logs themselves show that this.isPopupOpen is false?

1 Answers

@Input is used to pass data to the child component; to implement a callback you need to use @Output.

In your child component:

@Output() closeCallback = new EventEmitter();

// ...

close() {
  this.closeCallback.emit();
}

In your parent component:

<ng-container  *ngIf="isPopupOpen">
<e2-fullscreen-popup
  [title]="'top promotions'"
  (closeCallback)="closePopup($event)"
  >
...
</e2-fullscreen-popup>
</ng-container>
closePopup(dataFromChild: any){
  // handle callback
  this.isPopupOpen = false;
  console.log('this.isPopupOpen',this.isPopupOpen);
}

Related