- EmberJS Tutorial
- EmberJS - Home
- EmberJS - Overview
- EmberJS - Installation
- EmberJS - Core Concepts
- Creating and Running Application
- EmberJS - Object Model
- EmberJS - Router
- EmberJS - Templates
- EmberJS - Components
- EmberJS - Models
- EmberJS - Managing Dependencies
- EmberJS - Application Concerns
- EmberJS - Configuring Ember.js
- EmberJS - Ember Inspector
- EmberJS Useful Resources
- EmberJS - Quick Guide
- EmberJS - Useful Resources
- EmberJS - Discussion
Detaching and Tearing Down with willDestroyElement
You can remove the component elements from the DOM by triggering the willDestroyElement hook.
Syntax
import Ember from 'ember'; export default Ember.Component.extend ({ ... willDestroyElement() { //code here }, ... })
Example
The example given below describes the use of willDestroyElement hook, which removes the component elements from the DOM. Create a controller with name index and open the file from app/controller/ to add the following code −
import Ember from 'ember'; export default Ember.Controller.extend ({ showComponent: true, laterCount: 0, buttonText: Ember.computed('showComponent', function() { let showing = Ember.get(this, 'showComponent'); if (showing) { return 'Remove'; } else { return 'Add'; } }), actions: { toggleComponent() { this.toggleProperty('showComponent'); }, updateLaterCount() { Ember.set(this, 'laterCount', Ember.get(this, 'laterCount') + 1); } } });
Create a component with the name post-action, which will get defined under app/components/.
Open the post-action.js file and add the following code −
import Ember from 'ember'; export default Ember.Component.extend ({ runLater: null, didInsertElement() { let timeout = Ember.run.later(this, function() { Ember.Logger.log('fired this after 1 seconds...'); this.sendAction(); }, 500); Ember.set(this, 'runLater', timeout); }, willDestroyElement() { Ember.run.cancel(Ember.get(this, 'runLater')); } });
Now open the component template file post-action.hbs with the following code −
<h2>Tutorialspoint</h2>
Open the index.hbs file and add the following code −
<h5>Count for clicks: {{laterCount}}</h5> <button {{action 'toggleComponent'}}>{{buttonText}}</button> {{#if showComponent}} {{post-action action="updateLaterCount"}} {{/if}} {{outlet}}
Output
Run the ember server; you will receive the following output −
Initially number of clicks will be 1. When you click the Remove button, it will remove the text −
Next, click the Add button, it will increment the number of clicks and display the text −