Place block as component programmatically
Question
I've created a custom type, and a block
DomComponents.addType('MyComponent', { ... });
BlockManager.add('Component', { content: { type: 'MyComponent' } });
is it possible to insert it into DomComponents by name or any other means? I don't want to be drag'n'dropping the block manually each time. Thanks.
Answers (3)
Oh I found out how to do it -- via editor.addComponents({ type: 'MyComponent' }). Is there a way to insert it into a specific element by a CSS selector?
Found this snippet, but how would i find the correct index?
editor.getComponents().add('<div>Text</div>', {at: index});
ok so what i've done is
export default function iterateChildren(components, fn) {
components.each((model) => {
fn(model);
const childComps = model.get('components');
iterateChildren(childComps, fn);
});
}
export function findModels(components, selector) {
const found = [];
iterateChildren(components, (model) => {
const { view } = model;
if (!view) {
return;
}
const { el } = view;
const matches = el.matches(selector);
if (matches) {
found.push(model);
}
});
return found;
}
and then
const wrapper = DomComponents.getWrapper();
const models = findModels(wrapper.get('components'), '#hero .text');
models.forEach((model) => {
const components = model.get('components');
components.add({ type: 'ContainerPlugin' }, { at: 0 });
});
I think traversing the model tree would be a very good feature -- I'll work on the PR at some point. Cheers!
You can actually get the model from the cash element instance with view.$el.data('model'), so you might make it work with less code
wrapper.view.$el.find('#hero .text').each((el, i, $el) =>
console.log($el.data('model'))
)
Related Questions and Answers
Continue research with similar issue discussions.
Issue #1951
[QUESTIONS] change or add event on add component from block
is it possible ?, change the drag and drop event to on click when adding a new component, I want to add components by clicking the block th...
Issue #1432
[BUG] Custom DomComponent & Block let all elements duplicated
I created a Custom Block: and a Custom DomComponent: And a Custom Command (I found where error is happening): When I set the new link for c...
Issue #862
Jquery Image Viewer plugin in GrapesJs custom Block
I want to integrate Image viewer jquery plugin in grapesjs new custom block but jquery code doesn't recognize. How can write jquery code in...
Issue #1034
insert element or block inside parent element
Good day, i have component, have block i have Trait on listen changes, how can I add "h1 " inside that block "'<div class="container" style...
Paid Plugins That Match This Issue
Curated by issue keywords and label relevance to help you ship faster.
Loading paid plugin recommendations...
Browse Plugin Categories
Jump directly to plugin category pages on the marketplace.