Search code examples
angularjstree

Angular 7, implementing Jstree


I want to install jstree in my angular 7 project. I followed this tutorial https://dotnetdetail.net/how-to-add-treeview-in-angular-6-and-asp-net-core-application/

I have some problems. I think jstree is well installed, but i'm not sure it is well initialized, I tested two methods : the first one with html data and the other one with javascript array

this is my reproducible example : https://stackblitz.com/edit/angular-anjn4e

on my DOM i just have my first item , the others are push in the data but doesn't appear.

I don't have any console error so i think it's just a logic problem

thanks for your help


Solution

  • Inside your project in Angular :

    npm install --save jquery jstree
    
    npm install --save-dev @types/jquery @types/jstree
    

    Add into angular.json:

    styles: 
    "node_modules/jstree/dist/themes/default/style.min.css"
    
    scripts: 
    "node_modules/jquery/dist/jquery.min.js",
    "node_modules/jstree/dist/jstree.min.js"
    

    Example in your component.html:

        <div id="jstree">
        
            <ul>
                <li>Root node 1
                    <ul>
                        <li id="child_node_1">Child node 1</li>
                        <li>Child node 2</li>
                    </ul>
            </li>
                <li>Root node 2</li>
            </ul>
        </div>
        <button>demo button</button>
    

    In your component.ts

    import { Component, OnInit  } from '@angular/core';
    declare var $: any;
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent implements OnInit {
      title = 'tree';
      ngOnInit(): void {
        $(function () {
        // 6 create an instance when the DOM is ready
        $('#jstree').jstree();
        // 7 bind to events triggered on the tree
        $('#jstree').on("changed.jstree", function (e, data) {
          console.log(data.selected);
        });
        // 8 interact with the tree - either way is OK
        $('button').on('click', function () {
          $('#jstree').jstree(true).select_node('child_node_1');
          $('#jstree').jstree('select_node', 'child_node_1');
          $.jstree.reference('#jstree').select_node('child_node_1');
        });
      });
      }
    
    }