3

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

1 Answer 1

9

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"

Add installed type sets to tsconfig.app.json:

{
  ...
  "compilerOptions": {
    ...
    "types": ["chrome", "jquery", "jstree"]
  },
  ...
}

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');
    });
  });
  }

}
Sign up to request clarification or add additional context in comments.

2 Comments

Getting this error : error TS2339: Property 'jstree' does not exist on type 'JQuery<HTMLElement>'.
@ImranKhan try to import jquery to the component class: import * as $ from 'jquery'; import 'jstree';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.