angular 5 показать вложенные вопросы и ответить показать элемент под ним родительский элемент - PullRequest
0 голосов
/ 02 июня 2018

это мой ответ сервера для очередей и ответов .. это массив.

[
    {
        "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,
    },
]

второй элемент (id 2) является ответом на вопрос 1, потому что у него partent_id = 1, а id 3 независимвопрос

я хочу показать каждый ответ под своим вопросом в вложенном упорядоченном списке, если у вопроса есть какой-либо ответ .. как я могу это сделать?

я сделал что-то подобное, но мне кажется, что это совершенно неправильно, может кто-нибудь направить меня, чтобы сделать это правильно?спасибо

мой компонент для получения вопросов и ответов

  this._store.viewSingleProductQA(this.product.product_id).subscribe(data => {
      this.questions = data;

     this.responses = this.questions.filter(d => d.parent_id == this.questions.id)
    });

html:

  <div>{{question?.user}}</div>
  <div>{{question.text}}</div>
</div>
<div *ngFor="let res of responses">
  {{res.text}}
</div>

Ответы [ 2 ]

0 голосов
/ 02 июня 2018

Если есть только ответ (не ответ), вы всегда можете сделать

<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>

или «сопоставить» массив, чтобы создать новый список вопросов и ответов

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....
               }
          })

РЕДАКТИРОВАНИЕ: завершение ответа Мы можем сопоставить тоже как

this.questionAndAndwers=this.question
          .filter(q=>!q.parent_id)
          .map(q=>{
               return {...q,
                       answers:this.question.filter(i=>i.parent_id==q.id)
               }
          });

Или лучше, если есть ответ на ответ ответа ... мы можем сделать рекурсивную функцию

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)

Тогдамы можем сделать компонент

@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>
0 голосов
/ 02 июня 2018

Попробуйте этот HTML-код, где ответы выглядят следующим образом

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>

Установите флажок fiddle

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...