简体   繁体   English

如何在 Angular mat-tree 的子元素中显示数组

[英]How to display array in sub-elements of Angular mat-tree

I am a beginner in Angular and I want to display the value of an array in the child elements of the material tree.我是 Angular 的初学者,我想在材质树的子元素中显示数组的值。

For example, I want to display the name of the fruitList (Apple, Banana...) in the child element.The colors and discounts in the array need to be stored as variables, and they will be used elsewhere and cannot be removed.比如我想在子元素中显示fruitList的名称(Apple, Banana...)。数组中的colors和discounts需要作为变量存储,会在别处使用,不能去掉。

I have a working example here: stackblitz example我在这里有一个工作示例: stackblitz example

const TREE_DATA: FoodNode[] = [{
fruit: "fruit_1",
fruitList: [
  { name: "Apple", color: "red", discount: false },
  { name: "Banana", color: "yellow", discount: true },
  { name: "Grape", color: "purple", discount: true }
]},{
fruit: "fruit_2",
fruitList: [
  { name: "Lemon", color: "pale yellow", discount: false },
  { name: "Kiwi", color: "green", discount: false },
  { name: "Strawberry", color: "red", discount: true }
]}];

Can you please tell me how i can show the above json in my mat-tree?你能告诉我如何在我的 mat-tree 中显示上述 json 吗?

I provide for u sample for your specific data.我为您提供特定数据的样本。 in here这里

first of all you should write getChildren method then hasNestedChild:首先你应该写 getChildren 方法然后 hasNestedChild:

private _getChildren = (node: FoodNode): any => observableOf(node.fruitList);
  hasNestedChild = (_: number, nodeData: FoodNode) => {
    if (nodeData.hasOwnProperty("fruitList")) {
      return nodeData.fruitList.length > 0;
    }
    return false;
  };

then template:然后模板:

<mat-tree
  [dataSource]="nestedDataSource"
  [treeControl]="nestedTreeControl"
  class="example-tree mat-tree-position"
>
  <!-- Without Children -->
  <mat-tree-node *matTreeNodeDef="let node">
    <li class="mat-tree-node">
      <button mat-icon-button disabled></button>
      {{node.name}}
    </li>
  </mat-tree-node>

  <!-- With Children -->
  <mat-nested-tree-node *matTreeNodeDef="let node; when: hasNestedChild">
    <li>
      <div class="mat-tree-node">
        <button
          mat-icon-button
          matTreeNodeToggle
          [attr.aria-label]="'toggle ' + node.fruit"
        >
          <mat-icon class="mat-icon-rtl-mirror">
            {{nestedTreeControl.isExpanded(node) ? 'expand_more' :
            'chevron_right'}}
          </mat-icon>
        </button>
        <ng-container *ngIf="node.name"> {{node.name}} </ng-container>
        <ng-container *ngIf="node.fruit"> {{node.fruit}} </ng-container>
      </div>
      <ul [class.example-tree-invisible]="!nestedTreeControl.isExpanded(node)">
        <ng-container matTreeNodeOutlet></ng-container>
      </ul>
    </li>
  </mat-nested-tree-node>
</mat-tree>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM