Angular和TypeScript遍历对象 [英] Angular and TypeScript looping through object
问题描述
我正在尝试学习TypeScript和Angular.我有一个对象,我想循环遍历并拉出key:value对,以便可以在HTML中动态创建按钮.在HTML中,当我<< variable>>>
我的对象时,我得到"[object Object]"作为输出.当我执行标准 ng-repeat =变量中的o"
时,我什么也没得到.
I am trying to learn TypeScript and Angular. I have an object that I would like to loop through and pull key:value pairs so I can create buttons dynamically in HTML. In HTML when I <<variable>>
my object I get "[object Object]" as my output. When I do standard ng-repeat="o in variable"
I get nothing.
我的问题是如何遍历它,以便可以获取存储在该对象中的值.
My question is how do I loop through it so I can get values stored in that object.
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>
TypeScript
TypeScript
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() {
}
}
推荐答案
如果您使用的是angular 2,请使用 ngFor
而不是 ngRepeat
If are you using angular 2, then use ngFor
instead of ngRepeat
<div *ngFor="let o in menu_parts">
{{o}}
</div>
对于 [object object]
,您必须使用 json
过滤器将所有内容显示为JSON数组
As for [object object]
you have to use json
filter to show all the content a JSON array
{{menu_parts | json}}
这篇关于Angular和TypeScript遍历对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!