Home > Blockchain >  Radio button - Dynamic value causing failure
Radio button - Dynamic value causing failure

Time:09-29

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:

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.

CodePudding user response:

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

  • Related