0

我试图在角度 4 中创建动态树视图组件。我有一个数组,其中包含形成动态树视图的数据。

我试图创建一个自定义指令来实现这一点。这是我的代码:

import { Directive,ElementRef, Input, HostListener } from '@angular/core';

@Directive({
  selector: '[appTreeView]'
})
export class TreeViewDirective {

  @Input('appTreeView') categories:any;
  @Input() config:any = {
    categoryList: null,
    children : [],
    nodeLabel : '',
    treeId : '1',
    nodeId : '12'
  };
  elRef: any;
  constructor(el: ElementRef) {
    console.log(Element);
    console.log(this.config);
    console.log(this.categories);
    this.elRef = el;
  }

  ngOnInit(){
    console.log('input : ',this.categories);
    this.elRef.nativeElement.innerHTML = '<ul>' +
    '<li *ngFor="let node in ' + this.categories + '; let indx = index">' +
      '<i class="collapsed" data-ng-show="node.' + this.config.children + '.length && node.collapsed" data-ng-click="' + this.config.treeId + '.selectNodeHead(node)"></i>' +
      '<i class="expanded" data-ng-show="node.' + this.config.children + '.length && !node.collapsed" data-ng-click="' + this.config.treeId + '.selectNodeHead(node)"></i>' +
      '<i class="normal" data-ng-hide="node.' + this.config.children + '.length"></i> ' +
      '<span data-ng-class="node.selected" data-ng-click="selectNodeLabel(node)">{{node.' + this.config.nodeLabel + '}}</span>' +
      '<div data-ng-hide="node.collapsed" data-tree-id="' + this.config.treeId + '" data-tree-model="node.' + this.config.children + '" data-node-id=' + this.config.nodeId + ' data-node-label=' + this.config.nodeLabel + ' data-node-children=' + this.config.children + '></div>' +
    '</li>' +
  '</ul>';
  }


}

在我的组件 html 中:

<div [appTreeView]="categoryListArray"></div>

在组件 ts 中:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-tree-view-test',
  templateUrl: './tree-view-test.component.html',
  styleUrls: ['./tree-view-test.component.css']
})
export class TreeViewTestComponent implements OnInit {

  categoryListArray:any = [];
  constructor() { }

  ngOnInit() {
    this.categoryListArray = [
      { "label" : "User", "id" : "role1", "children" : [
        { "label" : "subUser1", "id" : "role11", "children" : [] },
        { "label" : "subUser2", "id" : "role12", "children" : [
          { "label" : "subUser2-1", "id" : "role121", "children" : [
            { "label" : "subUser2-1-1", "id" : "role1211", "children" : [] },
            { "label" : "subUser2-1-2", "id" : "role1212", "children" : [] }
          ]}
        ]}
      ]},
      { "label" : "Admin", "id" : "role2", "children" : [] },
      { "label" : "Guest", "id" : "role3", "children" : [] }
    ];
  }

  onCategoryClick(event){
    console.log('clicked item : ', event);
  }

}

这是输出如何得到:

树视图错误

请检查检查视图,我的代码未正确呈现。*ngFor 仍然存在,我可以在输出中看到插值符号。不知道为什么我的自定义指令不起作用。这是控制台输出以供参考。

树视图控制台输出

4

0 回答 0