ng不访问列表

时间:2017-11-25 21:49:00

标签: angular treeview ngfor

与另一个* ngFor相似,但解决方案并不起作用。这是树视图的骨架。 home模块html调用树视图组件。 HOME html

<div>
  home component before htr-tree-view
  <htr-tree-view></htr-tree-view>
  home component after htr-tree-view
</div>

主要组件重要部分:构造函数和ngOnInit

import { Component, OnInit } from '@angular/core';
import {TreeNode} from '../tree-view/TreeNode';
import {TreeViewComponent} from '../tree-view/tree-view.component';

@Component({
  selector: 'cs-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {

  constructor(private tree: TreeViewComponent) { }

  ngOnInit() {
    const firstNode = new TreeNode('0', 'All Projects', null);
    this.tree.addNode(null, firstNode);
  }
}    

TreeNode是该类的单个ts文件:

 export class TreeNode {
   id: string;
   name: string;
   canEdit: boolean;
   canDelete: boolean;
   canAdd: boolean;
   data: any;
   children: Array<TreeNode>;

   constructor(Id: string, Name: string, Data: any) {
     this.id = Id;
     this.name = Name;
     this.data = Data;
     this.canEdit = true;
     this.canDelete = true;
     this.canAdd = true;
     this.children = new Array<TreeNode>();
   }
 }

这将我们带到了非常简单的树视图组件。 HOME在ngOnInit期间调用它来addNode一个新节点。由于树是空的,它将节点推送到this.nodes上。我在这里以及随后的zone.run(我希望它会刷新屏幕)检查this.nodes内容,并且TreeNode出现在列表中。

树视图组件:

 import {Component, NgZone, OnInit} from '@angular/core';
 import {TreeNode} from './TreeNode';
 import {CommonModule} from '@angular/common';

 @Component({
   selector: 'htr-tree-view',
   templateUrl: './tree-view.component.html',
   styleUrls: ['./tree-view.component.scss']
 })
 export class TreeViewComponent implements OnInit {
   nodes: Array<TreeNode>;

   constructor(private zone: NgZone) {
     this.nodes = new Array<TreeNode>();
   }

   ngOnInit() {
   }

   addNode(Parent: TreeNode, NewNode: TreeNode) {
     if (Parent !== null) {
       Parent.children.push(NewNode);
     } else {
       this.nodes.push(NewNode);  <-- nodes has the new treenode here
     }
     this.zone.run(
       () => { console.log('refreshed');
                  console.log(this.nodes.length); <-- length is 1 here
       }
     );
   }
 }

TreeView HTML

 <div>
   tree-view.component.html start
   <table>
     <tbody>
     <tr *ngFor="let nxt of nodes">
       <td>N{{nxt.name}}</td>
       <td>I{{nxt.id}}</td>
     </tr>
     </tbody>
   </table>
   tree-view.component.html end
 </div>

浏览器的输出是:(鼓声)

 home component before htr-tree-view
 tree-view.component.html start
 tree-view.component.html end
 home component after htr-tree-view

我确信在监督下我会感到尴尬,但请事先感谢你的帮助。 瑜珈

0 个答案:

没有答案