【问题标题】:Angular Material Tree - Different parent/child typesAngular Material Tree - 不同的父/子类型
【发布时间】:2019-07-26 05:35:44
【问题描述】:

有没有办法利用材料树来表示父/子数据结构,其中子数据结构与父数据形状不同?我对这个组件的经验似乎表明数据结构需要是相同类型的递归。但是,我想用它来表示诸如 Orders(父级)和 Order Items(子级)之类的结构。这似乎不是受支持的用例。对吗?

自从 v2 推出以来,我一直在使用 Angular,并且从一开始我就一直在使用 Angular Material。在我看来,Tree 组件似乎是最繁琐且代码最难采样的组件。

【问题讨论】:

标签: angular angular-material


【解决方案1】:

我遇到了同样的问题,我选择的解决方案是为树组件制作一个扁平结构。结构具有来自父节点和子节点的所有字段(如果在父节点上使用模型,则子字段保持为空并且在子节点上相反)。似乎工作得很好。

发件人:

export interface ParentModel{
  id: number;
  name: string;    
  child: ChildModel[];    
}

export interface ChildModel{
  id: number;
  symbolName: string;    
  description: string;    
}

到:

export interface TreeModel {
  id: number;
  name: string; 
  symbolName: string;
  description: string;

}

【讨论】:

    【解决方案2】:

    周五晚些时候在工作中遇到了类似的问题,对结果不满意,因此模拟了一个可能满足您需求的 stackblitz。 @Jaikumar 的链接很有帮助 - https://material.angular.io/cdk/tree/api#NestedTreeControl

    查看这个修改后的 stackblitz - https://stackblitz.com/angular/lneeokqoxvm 基于 matTree 示例以获得一个工作示例。

    除了修改接口以适应松散的数据结构外,关键是在 NestTreeControl 中,最后的函数似乎是属性/函数 getChildren。

    interface FoodNode {
      name: string;
      children?: FoodNode[]; 
    }
    ...
    new NestedTreeControl<FoodNode>(node => node.children)
    

    修改为:

    interface FoodNode {
      name: string;
      children?: FoodNode[];
      subChildren?: FoodNode[]; 
    }
    
    ...
    
    new NestedTreeControl<FoodNode>(node => {
          return (node.children) ? node.children : node.subChildren;
    });
    

    类末尾的 hasChild 函数也必须考虑到增加的复杂性:

     hasChild (_: number, node: FoodNode): boolean {
       return (node.subChildren) ? 
        !!node.subChildren && node.subChildren.length > 0 : 
        !!node.children && node.children.length > 0;
      }
    

    双响!!让我找到了这个参考 - https://medium.com/better-programming/javascript-bang-bang-i-shot-you-down-use-of-double-bangs-in-javascript-7c9d94446054

    希望您发现这对您有所帮助,即使您在几个月前提出了这个问题。

    【讨论】:

      【解决方案3】:

      刚遇到同样的问题,由于没有可用的示例,我想出了以下解决方案。

      /**
       * Any class that implements toString is now usable inside a tree
       */
      export interface IString {
          toString : () => string;
      }
      
      /**
       * Node for to-do item
       */
      export interface Node {
          children? : Node[];
          item : IString;
      }
      
      /** Flat to-do item node with expandable and level information */
      export interface FlatNode {
          item : IString;
          level : number;
          expandable : boolean;
      }
      

      查看 Stackblitz:https://stackblitz.com/edit/angular-rwur5a

      【讨论】:

        猜你喜欢
        • 2013-08-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-11
        • 2019-05-08
        相关资源
        最近更新 更多