Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use javascript libraries that require binding to DOM nodes

Tags:

svelte

ag-grid

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?

enter image description here

like image 357
ivan quintero Avatar asked May 06 '19 19:05

ivan quintero


People also ask

What can JavaScript do with HTML DOM?

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.

What are the different types of nodes in Dom?

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.

What is the use of node in HTML?

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>.

What are the methods and properties of Dom in JavaScript?

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


1 Answers

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} />
like image 104
Tholle Avatar answered Sep 20 '22 03:09

Tholle