如何从递归结构中正确呈现html表

时间:2018-03-04 11:16:12

标签: html angular html-table

如何从Angular中的递归结构中正确呈现html表?

以下是我的尝试:https://stackblitz.com/edit/angular-gitter-usj76r

app.component.ts

import { Component} from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
  <table>    
    <recursivecomponent [elems]="data"></recursivecomponent>
  </table>
  `,
})
export class AppComponent  {
  data = [{
    name: "Root",
    children: [{
       name: "Level 1",
       children: [{
         name: "Level 2",
         children: []
       }]
    }]
  }];
}

recursive.component.ts

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

@Component({
  selector: 'recursivecomponent',
  template: `
    <div *ngFor="let el of elems;">
     <tr><td>{{el.name}}</td><td>Other cell</td></tr>
     <recursivecomponent [elems]="el.children"></recursivecomponent>
    </div>
  `
})
export class RecursiveComponent {
  @Input() elems: any[];  
}

期望的输出:

<table>
  <tr><td>Root</td><td>Other cell</td></tr>
  <tr><td>Level 1</td><td>Other cell</td></tr>
  <tr><td>Level 2</td><td>Other cell</td></tr>
</table>

0 个答案:

没有答案