angular 5 display nested questions and answer show item under it parent item

前端 未结 3 499
甜味超标
甜味超标 2021-01-22 09:37

this is my server response for quetions and answers.. its a array.

[
    {
        \"id\": 1,
        \"product\": 1,
        \"user\": \"alex\",
        \"text\         


        
3条回答
  •  轮回少年
    2021-01-22 10:36

    If only has a response (not a response of response) you always can do

    {{q.user}}{{q.text}}
    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: `
    {{q.user}}{{q.text}}
    ` }) export class QuestionComponent { @Input() questions: any; } //In our app.component

提交回复
热议问题