Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call destroy on a component from inside the component?

I have a modal component and I want to be able to destroy it when the user clicks on the x button, I also have a notification popup that destroys itself after an interval but I'd like to give the user the ability to close it with the x button too. I know I can pass an event to the component but I think it'll be better if the component is self destructive. Also there might be a better design for such case but that's the way I thought about it, other pointers will be appreciated.

like image 423
Yazan Rawashdeh Avatar asked Jun 01 '20 06:06

Yazan Rawashdeh


People also ask

How to destroy a component forcefully in Angular?

The ComponentRef of the newly created component and call the clear() method of ViewContainerRef destroys the existing view in the container. Add the destroy component. When we need to dynamically remove the component need to be please refer to the below clear function. Please follow the app.

Can angular component destroy itself?

If you add a component using ViewContainerRef. createComponent() like shown in Angular 2 dynamic tabs with user-click chosen components, then the component can destroy itself when you pass cmpRef to the created component.


1 Answers

If by destruction you mean node removal from the DOM, then all you need to do is obtain a reference to the top-most element in your component using Svelte's bind:this and remove said element using Node.removeChild():

<script>
  let nodeRef
</script>

<div bind:this={nodeRef}>
  <h3>Hey I'm a component</h3>
  <button on:click={() => nodeRef.parentNode.removeChild(nodeRef)}>
    Remove me :(
  </button>
</div>

Demo REPL

Edit

I had missed the point about suggesting a different approach. Since the display of the modal or notification will be triggered by the parent component (be it from a user action or as a programmatic response), it feels more natural to me that the parent would handle the dismissal of the modal or notification as well.

You don't have to use events to handle closing a modal or notification, you can simply pass a close handler as a prop. This will also save you from having to handle node removal yourself (or node create/append for that matter).

Something like the following would be more 'Svelte-like':

App.svelte

<script>
  import MyModal from './MyModal.svelte'

  let showModal = false
</script>

<div>
  {#if showModal}
    <MyModal onClose={() => showModal = false} />
  {/if}
  <button on:click={() => showModal = true}>Show Modal</button>
</div>

MyModal.svelte

<script>
  export let onClose
</script>

<div>
  <h3>Hi I'm a modal <span on:click={onClose}>X</span></h3>
</div>  

Demo 2 REPL

like image 171
Thomas Hennes Avatar answered Nov 08 '22 03:11

Thomas Hennes