Angular和TypeScript循环遍历对象

时间:2017-03-31 08:57:54

标签: javascript angular typescript

我正在尝试学习TypeScript和Angular。我有一个对象,我想循环并拉取键:值对,以便我可以在HTML中动态创建按钮。在HTML中,当我<<variable>>我的对象时,我得到了#34; [object Object]&#34;作为我的输出。当我做标准ng-repeat="o in variable"时,我什么也得不到。

我的问题是我如何遍历它以便我可以获得存储在该对象中的值。

HTML
    <div id="main_menu" class="container" role="main">
      <div class="container-fluid">
        <div class="row">
          <div class="page-header">WebJB</div>
          <div class="col-md-6">
            <div class="panel panel-default">
              <button href="#" class="panel-body btn btn-primary form-control">
                <h3 class="panel-title"></h3>
              </button>
          </div>


          <div ng-repeat="o in menu_parts"> <<--- I TRIED THIS
            {{menu_parts}}
          </div>


          </div>
        </div>
      </div>
    </div>

打字稿

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





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



export class IndexComponent implements OnInit {
  menu_parts = {
    "CRM": {
      "name": "CRM",
      "link": "/",
      "colour": "white",
      "label": "CRM"
    },
    "Admin": {
      "name": "Admin",
      "link": "/admin",
      "colour": "red",
      "label": "Admin"
    },
    "Dashboard": {
      "name": "Dashboard",
      "link": "/dashboard",
      "colour": "white",
      "label": "Dashboard"
    },
    "Settings": {
      "name": "Settings",
      "link": "/settings",
      "colour": "white",
      "label": "Settings"
    }
  }



  constructor(){
    var x = this.menu_parts;
    console.log(x);
  }

  ngOnInit() {

  }


}

1 个答案:

答案 0 :(得分:0)

如果您使用的是角度2,请使用ngFor代替ngRepeat

<div *ngFor="let o in menu_parts"> 
     {{o}} 
 </div>

对于[object object],您必须使用json过滤器来显示JSON数组的所有内容

{{menu_parts | json}}