我有一个带有类似对象的json
questions = [
{
question: "What is your name?",
options: [
{
option1 : "Abc",
}, {
option2 : "Def"
}, {
option3 : "Ghi"
}, {
option4 : "Jkl"
}
]
},
{
question: "Where is your Home Town?",
options: [
{
option1: "Abc"
}, {
option2: "Def"
}, {
option3: "Ghi"
}, {
option4: "Jkl"
}
]
}
]
在我看来,我想用像那样的ngfor渲染json
你叫什么名字?
- ABC
- def
- ghi
- jkl
questions = [{
question: "What is your name?",
options: [ "Abc", "Def", "Ghi", "Jkl"]
}, { {
question: "Where is your Home Town?",
options: [ "Abc", "Def", "Ghi", "Jkl"]
}]
<div *ngFor="let q of questions">
<span> {{q.question}}</span>
<ul>
<li *ngFor="option in q.options">{{option}} </li>
</ul>
</div>
您应该使用上述修改JSON格式
创建像这样的管道
import { PipeTransform, Pipe } from '@angular/core';
@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
transform(value, args:string[]) : any {
let keys = [];
for (let key in value) {
keys.push(key);
}
return keys;
}
}
像这样呼叫管道
<div *ngFor="#q of questions">
<span> {{q.question}}</span>
<ul>
<li *ngFor="#option of q.options ">
<span *ngFor="#key of option | keys ">{{key}} : {{option[key]}} </span>
</li>
</ul>
</div>