How can I make component not removable after init in grapesjs?

1.2k views Asked by At

I have grapesjs editor with mjml plugin and I decided to mark some components as not removable to protect users from remove critical parts of email template.

Sugested way how to do this set attribute of mjml element like this:

<div data-gjs-removable="false">...</div>

But it does not work for <mjml> and <mj-body> tags.

Can I do this after load a template?

1

There are 1 answers

0
Vladimír Mlázovský On

yes you can.

After init of editor you need to traverse ComponentDom and set componenets to not removable. Do not forget to remove button from toolbox - it will not work anyway.

const editor = grapesJS.init({...});

editor.on('load', () => {

    const notRemovableTags = ['mjml', 'mj-body'];

    // recursive function to traverse component tree
    const updateRecursive = componentModel => {
      
        if (notRemovableTags.indexOf(componentModel.attributes.tagName) !== -1) {
            // set not removable
            componentModel.set({removable: false});
            // remove remove icon from toolbar
            componentModel.set({
               toolbar: componentModel.get('toolbar')?.filter(tlb => tlb.command !== 'tlb-delete')
            });
        }
        // recurse
        componentModel.get('components').each(model => updateRecursive(model));
    }
    // start recursion
    updateRecursive(this.editor.DomComponents.getComponent());
});