mat-accordion 递归调用角度分量时出现滞后

Abh*_*kar 1 tree recursion components angular angular8

我在手风琴中递归地调用组件以显示树状结构。

该代码适用于短输入,但在嵌套数据的递归调用上滞后

它就像一棵 json 树。

//sample.component.html
<app-tree [input]="data"></app-tree>


//tree.component.html

    <mat-accordion>
        <mat-expansion-panel hideToggle="true" (click)="toggleTree($event, input)">
          <mat-expansion-panel-header>
            <mat-panel-title>
                <mat-icon>{{input.buttonName}}</mat-icon>
                {{input.key}}
            </mat-panel-title>
          </mat-expansion-panel-header>
          <ul class="main-obj">   // tried *ngIf here
             <div class="obj-list" *ngFor="let item of input.value; trackBy: trackChanges">
                <li>
                  {{item.key}}: {{item.value}}
                </li>
                <li style="list-style: none; margin-left: -40px;">
                    <app-tree [input]="item"></app-tree>
                </li>
            </div>
         </ul>
        </mat-expansion-panel>
    </mat-accordion>

//tree.component.ts

    import { Component, OnInit, Input, Output } from '@angular/core';
    import { EventEmitter } from 'events';

    @Component({
      selector: 'app-tree',
      templateUrl: './tree.component.html',
      styleUrls: ['./tree.component.css']
    })

    export class TreeComponent implements OnInit {
        @Input() input: any;

        @Output() click = new EventEmitter();

        constructor(){}

        ngOnInit(){
        }

        toggleTree(event, toggleButton) {
            event.stopPropagation();
            if(toggleButton.buttonName == 'add')  
                toggleButton.buttonName = 'remove';
            else
                toggleButton.buttonName = 'add';
        };

        trackChanges = (index) => {
            return index;
        }
    }
Run Code Online (Sandbox Code Playgroud)

我尝试放置 ngIf (如 ngFor 之前的代码所示),但效果不是很好。

打开手风琴时有什么办法加载组件吗?

谢谢!

jpa*_*vel 5

回答你的问题:

打开手风琴时有什么办法加载组件吗?

是的,有,但我不确定它是否能解决滞后问题。无论如何,尝试将扩展面板的内容包装在ng-template包含该属性的matExpansionPanelContent属性中。它会延迟加载其内容(请参阅文档)。

<mat-accordion>
  <mat-expansion-panel hideToggle="true" (click)="toggleTree($event, input)">
    <mat-expansion-panel-header>
      <mat-panel-title>
        <mat-icon>{{input.buttonName}}</mat-icon>
        {{input.key}}
      </mat-panel-title>
    </mat-expansion-panel-header>

    <ng-template matExpansionPanelContent>
      <ul class="main-obj">   // tried *ngIf here
        <div class="obj-list" *ngFor="let item of input.value; trackBy: trackChanges">
          <li>{{item.key}}: {{item.value}}</li>
          <li style="list-style: none; margin-left: -40px;">
            <app-tree [input]="item"></app-tree>
          </li>
        </div>
      </ul>
    </ng-template>
  </mat-expansion-panel>
</mat-accordion>
Run Code Online (Sandbox Code Playgroud)