簡體   English   中英

如何在 angular 7 中使用 ngFor 將嵌套的 json 循環到 ul li

[英]How to loop nested json into ul li using ngFor in angular 7

I have a nested json,I need to append that json format into ul li tag using ngFor as per below output format,I can use ngfor loop but I am not getting how to use it.Here is the expected output(hardcoded) in html .下面是代碼。

home.component.html

<div class="col-md-3" id="leftNavBar">
  <ul>
    <li class="parentNav">parent1</li>
    <li class="childData">
      <ul>
        <li>child11<span class="pull-right"><input type="checkbox"></span></li>
        <li>child12<span class="pull-right"><input type="checkbox"></span></li>
      </ul>
    </li>
  </ul>
  <ul>
    <li class="parentNav">parent2</li>
    <li class="childData">
      <ul>
        <li>child2<span class="pull-right"><input type="checkbox"></span></li>
      </ul>
    </li>
  </ul>
  <ul>
    <li class="parentNav">parent3</li>
    <li class="childData">
      <ul>
        <li>child3<span class="pull-right"><input type="checkbox"></span></li>
      </ul>
    </li>
  </ul>

</div>

home.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit { 

    nestedjson:any;
 constructor(private formBuilder: FormBuilder) {


     }

  ngOnInit() {
      this.nestedjson = [{"name":"parent1","value":["child11","child12"]},{"name":"parent2","value":["child2"]},{"name":"parent3","value":["child3"]}];

} 




}

這是非常基本的。 你應該先自己試試。

在此處輸入圖像描述

<div class="col-md-3" id="leftNavBar">
    <ul *ngFor="let nested of nestedjson">
        <li class="parentNav">{{ nested.name }}</li>
        <li class="childData">
            <ul>
                <li *ngFor="let val of nested.value">{{ val }}<span class="pull-right"><input type="checkbox"></span></li>
            </ul>
        </li>
    </ul>
</div>

Stackblitz: https://stackblitz.com/edit/angular-mhtnsd

試試這樣:

工作演示

<div class="col-md-3" id="leftNavBar">
  <ul *ngFor="let item of nestedjson">
    <li class="parentNav">parent1</li>
    <li class="childData">
      <ul>
        <li *ngFor="let child of item.value">{{child}}<span class="pull-right"><input type="checkbox"></span></li>
      </ul>
    </li>
  </ul>
</div>

解決方案如下。 檢查stackblitz 您的解決方案與 ngFor 並列。

<div class="col-md-3" id="leftNavBar">
  <ul *ngFor="let parent of nestedJson">
    <li  class="parentNav">{{parent.name}}</li>
    <li class="childData">
      <ul>
        <li *ngFor="let child of parent.value" >{{child}}<span class="pull-right"><input type="checkbox"></span></li>
      </ul>
    </li>
  </ul>
</div>

如果您有 JSON 字符串,那么您將需要使用 JSON.parse() 來獲取上述格式的 object。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM