Angular 2 - Dynamic Reactive form with Radio Inputs build with FormBuilder, FormGroup, FormArray

638 views Asked by At

Case: I have an array of answers which I want to show in the view as radio inputs. When one of the answers is already answered it must be [checked] and if it's [checked] a textarea shows, so far so good.

Next I want to check another radio input and I want the current selected to be deselected and its textarea hidden, then the new selected radio input should be [checked] and it's textarea should show.

I use the FormBuilder and FormArray and have following issues.

  • I can't use index without intrapolation, I see many examples where the index is used without.
  • If I select another radio input, first my data disappears and it's not checked and on the second click it get's checked but now both are checked.

initial state clicked on another radio

enter image description here - I don't have access to the checked event, I can show it in the view with {{tempVar.checked}} as you can see above, if I use a template variable #tempVar, but I don't have access to it in the textarea below *ngIf="tempVar.checked". If I do use it in the ngIf I get the following error

Expression has changed after it was checked. Previous value: 'false'. Current value: 'true'.

Questions:

  • Is this the right approach?
  • An example of a Reactive Dynamic form with FormBuilder and FormArray with Radio inputs

Here is my code https://gist.github.com/webwizart/121c85a0f316f47977cc0c99455af7bf

1

There are 1 answers

0
GoldFlow On

I would think using the tags should be reserved for unique identifiers? I wouldn't be surprised if dom renderer will update all elements with the same id.

Not sure if this will help, but you could use an answer view model instead (containing the same data) but that also has a 'checked' property

This way you can be sure that it will behave as you would expect.

e.g.: (in your component.ts)

let answers =  this.question.Question.PossibleAnswers
.map(a => 
 { return Object.assign({}, a, { checked: false });
 }
);

then in html you use: 'answer.checked' instead of 'radio.checked'

ps: also you could use ng-container instead of span, so you don't have an extra DOM imprint in your html