渲染列表项时显示无限点

时间:2019-05-08 09:00:18

标签: angular typescript

我正在尝试渲染嵌套列表元素,

下面是JSON结构,

listItems = {
  "text": "root",
  "children": [{
    "text": "Level 1",
    "children": [{
      "text": "Level 2",
      "children": [{
        "text": "Level 3",
        "children": [],
        "type": "unordered-list-item"
      }],
      "type": "unordered-list-item"
    }],
    "type": "unordered-list-item"
  }],
  "type": "unordered-list-item"
}

下面是我的html组件

<ul *ngIf="listItems.type === 'unordered-list-item' && listItems.children.length > 0">
  <li *ngFor="let child of listItems.children">
    {{ child.text }}

    <bw-list *ngIf="child.type === 'unordered-list-item'" [listItem]="child"></bw-list>
  </li>
</ul>

如果找到children,则需要重复该组件并渲染子代。

Component.ts

export class AppComponent {
  @Input() listItem: any;
  public listItems = {
    "text": "root",
    "children": [{
      "text": "Level 1",
      "children": [{
        "text": "Level 2",
        "children": [{
          "text": "Level 3",
          "children": [],
          "type": "unordered-list-item"
        }],
        "type": "unordered-list-item"
      }],
      "type": "unordered-list-item"
    }],
    "type": "unordered-list-item"
  };
}

问题是它渲染无限点。请帮助

链接到项目https://stackblitz.com/edit/angular-list-component-1smik4?file=src/app/app.component.ts

2 个答案:

答案 0 :(得分:0)

我没有收到您的代码。您忘记减少长度数字了吗?也许这可以帮助您:

import {Component, Input} from "@angular/core";

@Component({
    selector: 'my-app',
    template: `
    <div>
      Recursive Component
      <my-app [counter]="counter - 1" *ngIf="counter > 0"></my-app>
    </div>
  `
})
export class AppComponent {

    @Input() counter : number = 3;

}

答案 1 :(得分:0)

将此行添加到app.component.html

<app-recursion *ngFor="let subChild of listItems.children" [child]="subChild"></app-recursion>

查看此代码-https://stackblitz.com/edit/angular-list-component-kpd6fm