Search code examples
javascriptwebmaterial-designmaterial-componentsmaterial-components-web

MDC web components: mdc-dialog doesn't close properly sometimes


I use MDC-Web components. I'm opening and closing a dialog programmatically, but sometimes it doesn't close. I don't know if I am doing the right way in order to close the dialog.

closeDialog('dialog_gui');

function closeDialog(elementId){
    let dialog = new mdc.dialog.MDCDialog(document.getElementById(elementId));
    dialog.close();
}

Solution

  • Your function creates the new instance of MDCDialog every time dialog gets closed. You should store the instance of dialog outside the closing function:

    const dialog = new mdc.dialog.MDCDialog(document.getElementById('dialog_gui'));
    
    function closeDialog() {
      // some stuff
      dialog.close();
    }
    
    closeDialog();
    

    Also, you can close dialog without extra function, just using MDCDialog's close() method:

    const dialog = new mdc.dialog.MDCDialog(document.getElementById('dialog_gui'));
    
    dialog.close();
    

    Here is the Codepen example where dialog will be opened, and then closed after 3 seconds.