首页 > 解决方案 > Angular 4 - 如何正确导入fancytree

问题描述

我试图将 fancytree 导入我的 Angular 4 项目。我按照这个指令做了一切: https ://github.com/mar10/fancytree/wiki/TutorialIntegration#howto-run-fancytree-with-angular-4

但最后每次我得到错误

$(...).fancytree 不是函数

该指令中是否缺少某些内容..?

到目前为止我所做的:

  1. npm install --save jquery jquery.fancytree
  2. 向 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. 在 tsconfig.app.json 中添加类型:
{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "module": "es2015",
    "baseUrl": "",
    "types": ["jquery","jquery.fancytree"]
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ]
}
  1. 在组件的 html 中添加树 id:
<div id="tree">

</div>
  1. 尝试在组件中使用:
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');
  }

}

标签: angularfancytree

解决方案


好的,找到了!组件中确实需要这些:

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

或者如果有人喜欢:

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

并在我们需要的组件中使用 fancytree 对象:

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

推荐阅读