我的问题很简单,我有一个下面的JSON Typescript对象,我想迭代遍历JSON属性
{"work_type":"Fabricación","work_type_resp":"Mesa","looking_for":"Relación Calidad/Precio","image":"https://s3-sa-east-1.amazonaws.com/online-quotation-images/153366018967.png","width":"22","high":"34","depth":"","modifications":"mod"}
使用的代码是以下有角TypeScript组件:
export class DetailsOnlineQuoteModalComponent implements OnInit {
@Input() title;
@Input() values:string;
properties:JSON;
constructor(public activeModal: NgbActiveModal) { }
ngOnInit() {
this.properties=JSON.parse(this.values);
console.log(this.properties);
}
}
我真正需要的是遍历JSON的键值属性,并在我的HTML中显示它们。
非常感谢!
答案 0 :(得分:8)
如果您使用的是Angular 6.1,请使用键值管道
<div *ngFor="let title of data | keyvalue">
{{title.key}}
</div>
对于Angular 5
<div *ngFor="let key of dataKeys">
{{key}} ------------- {{data[key]}}
</div>
get dataKeys() { return Object.keys(this.data); }
答案 1 :(得分:4)
根据您的评论,我假设您要在HTML上执行ngFor以显示每个键值对
<div *ngFor="let key of Object.keys(properties)">
{{properties[key]}} --> this is the value
</div>
答案 2 :(得分:3)
您可以使用Object.Keys获取所有键,并按如下所示分配给变量,
this.properties=JSON.parse(this.values);
let response = Object.keys(this.propertie);
现在您可以在其上使用ngFor
<div *ngFor="let key of response ">
{{properties[key]}}
</div>
答案 3 :(得分:0)
let obj = {"work_type":"Fabricación","work_type_resp":"Mesa","looking_for":"Relación Calidad/Precio","image":"https://s3-sa-east-1.amazonaws.com/online-quotation-images/153366018967.png","width":"22","high":"34","depth":"","modifications":"mod"}
this.keyOfObj = Object.keys(obj);
<div *ngFor="let key of keyOfObj ">
{{obj[key]}}
</div>
答案 4 :(得分:0)
不幸的是,似乎无法在ANGULAR_9上使用键值对
请参见此处,以比较完全不同的做事方式:https://stackblitz.com/edit/angular9-iterate-on-object-attribute
否则,通过定义执行此工作的方法的答案仍然有效。