[SalesForce] How to Remove a Lightning Component from the DOM

I have been reading through the Lightning Developer Guide. Could someone tell me if it is possible to remove a Lightning Component from the DOM? The use case I have is that I am displaying a success or error message based on a record update in Salesforce. I have that error message showing for 5 seconds, and then it will automatically be removed from the body of the <div> where I inserted it. However, it still remains in the DOM. I am using the $A.createComponent() method to create the ui:message component dynamically and was thinking that I would want to remove it from the DOM so that new ui:message components are not continually added each time.

Could someone provide some insight?

Thanks!

Best Answer

You can use facets to do this. For example, a simple test.app:

<aura:application access="GLOBAL">
    <aura:attribute name="messages" type="Aura.Component[]" access="GLOBAL"/>
    <div aura:id="messages">
        {!v.messages}
    </div>
    <ui:button label="Show Message" press="{!c.showMessage}"/>
</aura:application>

The corresponding testController.js:

({
    showMessage: function(component, event, helper) {
        $A.createComponent("ui:outputText",
                           {value: "Message created at " + Date.now()},
                           function(cmp) {
                               component.set("v.messages", [cmp]);
                               setTimeout(function() {
                                   $A.run(function() {
                                       component.set("v.messages", []);                                       
                                   });
                               }, 5000)
                           });
    }    
})

The facet is an attribute of type Aura.Component[] that you render in the desired spot using an expression such as {!v.messages}. When the element is created, set the value of this facet to be an array with one component, the [cmp] in the code. Set a timeout, etc., then set the value of this facet to be an empty array with []. Make sure to wrap the calls with $A.run.

If you use the Chrome or other tools to inspect the DOM, you'll see the component elements appear and disappear.

If this isn't what you're looking for, please provide more details.