I have been trying to use Ag-Grid with Svelte. I understand that the main problem with using this grid library is that it needs to bind to a dom element that may not exist at the time of the code executing. For example:
// lookup the container we want the Grid to use
var eGridDiv = document.querySelector('#myGrid');
In this case, the #myGrid element does not exist yet.
I have tried creating an element and then placing it on the HTML part of the Svelte component, like this.
let eGridDiv = document.createElement("DIV");
let gridOptions = { columnDefs: columnDefs, rowData: $orders };
new Grid(eGridDiv, gridOptions);
And then down on the HTML section
<eGridDiv />
However, the new element does not seem to be initialized by Ag-Grid.
So what is the recommended way to use these types of libraries in Svelte?
With the HTML DOM, JavaScript can access and change all the elements of an HTML document. When a web page is loaded, the browser creates a D ocument O bject M odel of the page.
Before starting working on the DOM, we should understand the following terminologies related to DOM: Element node: It represents any element that exists in the DOM. Root node: This is the top node in the tree, which in the case of HTML, is always the "HTML" node. Child node: This is a node that is directly inside another node.
It is a property that we use to get or set the HTML or XML markup contained within the element. Also, its syntax looks like below: Syntax: node.innerhtml= “changingText”; Where, node: is any web element that can be found on the web page usingdocument.getElementBy<Id/tagName/className>.
Apart from accessing the elements, JavaScript provides some methods and properties which can manipulate or change the values of the DOM elements. Few of those methods and properties are: write innerHTML attributeName Style.property setAttribute createElement appendChild removeChild replaceChild
If you want to use a DOM node in the script part of your component you can use the bind:this={domNode}
element binding to get a reference to it, and then use it after the component has been rendered in onMount
.
<script>
import { onMount } from 'svelte';
let domNode;
// ...
onMount(() => {
const gridOptions = { columnDefs: columnDefs, rowData: $orders };
new Grid(domNode, gridOptions);
});
</script>
<div bind:this={domNode} />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With