this is my server response for quetions and answers.. its a array.
[
{
\"id\": 1,
\"product\": 1,
\"user\": \"alex\",
\"text\
Accepted answer Working for one level question. If really want to work in nested scenario: Please check below option
export class QuestionList
{
questions:Question[];
}
export class Question
{
text:string;
answer:Answer;
nextquestions:QuestionList;
}
export class Answer
{
text:string;
}
@Component({
selector: 'question-view',
template: `<ul>
<li *ngFor="let q of questions">
{{q.text}}:{{q.answer.text}}
<question-view [questions]=q.nextquestions></question-view>
</li></ul>`
})
export class QuestionViewComponent {
@Input() questions: any[];
}
Try this HTML, where responses is as follows
responses = [
{
"id": 1,
"product": 1,
"user": "alex",
"text": "is it ok?",
"parent_id": null,
},
{
"id": 2,
"product": 1,
"user": "john doe",
"text": "yes its ok.",
"publish": true,
"parent_id": 1,
},
{
"id": 3,
"product": 1,
"user": "shiva",
"text": "how can i .. . .",
"publish": true,
"parent_id": null,
},
]
<div *ngFor="let res of responses">
<div *ngIf="res.parent_id === null">
Ques : {{res.text}}
<br/>
Answers :
<ng-container *ngFor="let res2 of responses">
<div *ngIf="res2.parent_id === res.id">
{{res2.text}}
</div>
</ng-container>
</div>
</div>
Check this fiddle
If only has a response (not a response of response) you always can do
<div *ngFor="let q of questions>
<!--only want to show the question, not the answer-->
<div *ngIf="!q.parent_id>
{{q.user}}{{q.text}}
<div *ngFor="let a of question.filter(t=>t.parent_id==q.id)>
response:{{a.user}}{{a.text}}
</div>
<div>
</div>
or "map" the array to create a new list of question and answer
this.questionAndAndwers=this.question
.filter(q=>!q.parent_id)
.map(q=>{
let answer=this.question.find(i=>i.parent_id==q.id)
return {...q,
a_user:answer?answer.user:null,
a_text:answer?answer.text:null
..others properties....
}
})
EDITED: completing the answer We can map too like
this.questionAndAndwers=this.question
.filter(q=>!q.parent_id)
.map(q=>{
return {...q,
answers:this.question.filter(i=>i.parent_id==q.id)
}
});
Or better if there are reply of reply of reply... we can make a recursive function
getAnswers(questions:any,id:any)
{
return questions
.filter(i=>i.parent_id==id)
.map(q=>{
return {...q,
answers:this.getAnswers(questions,q.id)}
})
}
//And
this.questionAndAndwers=this.getAnswers(this.question,null)
Then we can make a component
@Component({
selector: 'app-question',
template: `<div *ngFor="let q of questions">
{{q.user}}{{q.text}}
<app-question [questions]=q.answers></app-question>
</div>`
})
export class QuestionComponent {
@Input() questions: any;
}
//In our app.component
<app-question [questions]="questionAndAndwers"></app-question>