Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Radio button – Dynamic value causing failure

I’ve been trying to turn arround this problem for a while, maybe some of you have an answer.
The exercise is simple, I’m trying to create an input in a *ngFor loop.

But the radio buttons don’t work this way…

TS Code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

get datas(): {radio:number}[] {
    return [
      {radio: 1},
      {radio: 2},
      {radio: 3},
      {radio: 4},
      {radio: 5},
      {radio: 6},
    ]
  }

  ngOnInit() {
    this.testForm = this.fb.group({
      radios: [1]
    });
  }

  change(val: number): void {
    this.testForm.get('radios')?.setValue(val);
  }

I have made up this change method so I can reproduce the radio option change.

HTML Code:

<form [formGroup]="testForm">
  <ng-container *ngFor="let data of datas">
    <input type="radio" [value]="data.radio" [name]="'radios'" [formControlName]="'radios'">
  </ng-container>
other
  <input type="radio" [value]="4" [name]="'radios'" [formControlName]="'radios'">
  <input type="radio" [value]="5" [name]="'radios'" [formControlName]="'radios'">
  <input type="radio" [value]="6" [name]="'radios'" [formControlName]="'radios'">
</form>

{{ testForm.value | json }}

No clue why the other radio input works, but not the above ones. I tried the [attr.value] too, but in this cas it is not usefull and even break things more.

>Solution :

When you using get datas everytime a change happen, it will call get datas a time. Which is generate the whole new object that can’t match any old one.
You can try this

// change from:
  // get datas(): {radio:number, id: number}[] {
  //   return [
  //     {radio: 1},
  //     {radio: 2},
  //     {radio: 3},
  //     {radio: 4},
  //     {radio: 5},
  //     {radio: 6},
  //   ]
  // }
// to:
  datas = [
    { radio: 1 },
    { radio: 2 },
    { radio: 3 },
    { radio: 4 },
    { radio: 5 },
    { radio: 6 },
  ];

or this

  sampleData = [
    { radio: 1 },
    { radio: 2 },
    { radio: 3 },
    { radio: 4 },
    { radio: 5 },
    { radio: 6 },
  ];


  get datas(): { radio: number }[] {
    // console.log(1); <= unrem to check when it call
    return this.sampleData;
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading