Angular-Handle nested array in radio-button

71 Views Asked by At

I am working on a project where I have to work with a nested array This is a dummy version of the data

 options = [
   {
     value: 1,
     text: 'Cheeseburger',
     content: [
       { id: 101, name: 'Cheese' },
       { id: 102, name: 'Bread' },
       { id: 103, name: 'Veggies' },
     ],
   },
   {
     value: 2,
     text: 'Taco',
     content: [
       { id: 201, name: 'Nun' },
       { id: 202, name: 'Veggies' },
       { id: 203, name: 'Sauce' },
     ],
   },
 ];

Using this I have to make a MCQ style question and answer using radio button. While I was able to make the question and answer set. I am facing two problems.

  1. I have a 'Add More' button, which when clicked creates a new empty set of question & answer(makes a clone of the 'options'). But in doing so the previously selected options gets de-selected even though I can see that the answers are stored in the array.
  2. I have to patch an API response to this radio button. This is the dummy version of the API response:
 res = [
      [102, 201],
      [101, 202],
    ];

I want the options to get selected accordingly, i.e in the dummy data there are two arrays. Then in the UI, the question and answers should have two two sets and the options to be selected based on the id of the contents array with that of the res.

For 1, I did this

  addMoreQuestions() {
    const existingQuestionSet = this.questionandAnswer[0].slice();
    console.log('existingQuestionSet =>', existingQuestionSet);

    this.questionandAnswer.push(existingQuestionSet);
    console.log('this.questionAnswer =>', this.questionandAnswer);

    // Copy the selected options for the previous question sets
    const previousSelectedOptions = [...this.selectedOptions];

    this.answers.push(previousSelectedOptions);
    console.log('answer =>', this.answers);

    // Reset selectedOptions only for the new question set
    this.selectedOptions = [];
  }

Here I am seeing pushing a new array inside the questionandAnswer,but in doing so the previously selected options get de-selected. But I can see it in 'this.answers' For 2,I am unable to think of a way to proceed. Can anybody help this? This is the stackblitz link

Thanks for the help,in advance.

0

There are 0 best solutions below