gpt4 book ai didi

javascript - Angular 和 TypeScript 循环遍历对象

转载 作者:搜寻专家 更新时间:2023-10-30 22:00:40 25 4
gpt4 key购买 nike

我正在尝试学习 TypeScript 和 Angular。我有一个对象,我想遍历并拉出键:值对,以便我可以在 HTML 中动态创建按钮。在 HTML 中,当我 <<variable>>我的对象我得到“[object Object]”作为我的输出。当我做标准时 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>

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

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

至于[object object]你必须使用json过滤器来显示一个JSON数组的所有内容

{{menu_parts | json}}

关于javascript - Angular 和 TypeScript 循环遍历对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43136531/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com