angularfancytree

Angular 4 - how to correctly import fancytree


I was trying to import fancytree to my Angular 4 project. I did everything according to this instruction: https://github.com/mar10/fancytree/wiki/TutorialIntegration#howto-run-fancytree-with-angular-4

But in the end every time I get error

$(...).fancytree is not a function

Is something missing in this instruction..?

What I did until now:

  1. npm install --save jquery jquery.fancytree
  2. Added scriptes and styles to angular-cli.json:
[...]
"styles": [
        "../node_modules/bootstrap/dist/css/bootstrap.min.css",
        "../node_modules/ngx-bootstrap/datepicker/bs-datepicker.css",
        "../node_modules/jquery.fancytree/dist/skin-win8/ui.fancytree.min.css",
        "styles.scss"
      ],
      "scripts": [
        "../node_modules/jquery/dist/jquery.min.js",
        "../node_modules/bootstrap/dist/js/bootstrap.min.js",
        "../node_modules/jquery.fancytree/dist/jquery.fancytree-all-deps.min.js"
      ],
[...]
  1. Added types in tsconfig.app.json:
{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "module": "es2015",
    "baseUrl": "",
    "types": ["jquery","jquery.fancytree"]
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ]
}
  1. Added tree id in the component's html:
<div id="tree">

</div>
  1. Tried to use in the component:
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
// const fancytree = require('jquery.fancytree'); // doesn't work
import * as $ from 'jquery';

@Component({
  selector: 'table-of-content',
  templateUrl: './table-of-content.component.html',
  styleUrls: ['./table-of-content.component.scss']
})
export class TableOfContentComponent implements OnInit {

  @Output() isTocClosed: EventEmitter<boolean> = new EventEmitter<boolean>();

  constructor() { }

  ngOnInit() {
    $('#tree').fancytree({
      extensions: ['edit', 'filter'],
      source: [
        { title: "Node 1", key: "1" },
        {
          title: "Folder 2", key: "2", folder: true, children: [
            { title: "Node 2.1", key: "3" },
            { title: "Node 2.2", key: "4" }
          ]
        }
      ]
    });

    // const tree = fancytree.getTree('#tree');
  }

}

Solution

  • Ok, found it! Those are really needed in the component:

    import 'jquery.fancytree/dist/modules/jquery.fancytree.edit';
    import 'jquery.fancytree/dist/modules/jquery.fancytree.filter';
    

    or if someone prefer:

    require('jquery.fancytree/dist/modules/jquery.fancytree.edit');
    require('jquery.fancytree/dist/modules/jquery.fancytree.filter');
    

    And to use fancytree object in the component we need:

    const fancytree = require('jquery.fancytree');