0

I have an 'inline notification' component that looks like this:

enter image description here

What I'm trying to accomplish is properly self-destructing the Component when the X-icon at the top-right is clicked.

I currently have the following to accomplish that, based on this SO answer:

@Component({
  selector: 'sf-inline-notification',
  templateUrl: './inline-notification.component.html',
  styleUrls: ['./inline-notification.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class InlineNotificationComponent implements OnDestroy {
  private readonly _selfRef = inject(ElementRef<HTMLElement>);
  ... // Some irrelevant @Input() and private variables

  // eslint-disable-next-line @angular-eslint/no-empty-lifecycle-method
  ngOnDestroy(): void {
    // Although empty, it's added on purpose, since we ALWAYS want to call it when closing the Inline Notification
    // Add cleanup if necessary (e.g. unsubscribe observables; stop timers; unregister callbacks; stop event emitters; etc.)
  }

  protected closeNotification(): void {
    this.ngOnDestroy();
    this._selfRef.nativeElement.remove(); // Remove itself from the DOM
  }

  ... // Some irrelevant getters/setters used in its HTML-template
}

closeNotification is called with (click)="closeNotification()" when the icon is clicked.

It works as intended visually: it removes itself from the DOM. But I'm a bit concerned about potential missed garbage collection and other cleanup of the Angular framework, which it usually does when a component is hidden/removed/destroyed.
Is there a better way to handle this programmatically in this Component itself (without any modifications necessary to the parent component where this inline-notification might be added to)?

Kevin Cruijssen
  • 9,153
  • 9
  • 61
  • 135

0 Answers0