简体   繁体   中英

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

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.

初始状态 点击了另一个电台

在此处输入图片说明 - 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

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.

eg: (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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM