1

I have created a array like this

this.list= [{
      id: 1,
      value: 'One',
      checked: true
    },
      {
        id: 2,
        value: 'Two'
      }];

and i tried to do Two way binding like this

<ul *ngFor="let data of list;">

            <div  class="radio" >
              <label>
                <input type="radio" name="sex" [(ngModel)] = "data.checked" [checked]="data.checked">{{data.value}}
</ul>

but it doesn't work i want dynamically update the checked variable when radio button is clicked

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Kokulan
  • 1,316
  • 3
  • 19
  • 35
  • You can't use a radio button like a checkbox. You have to declare a value for each inputs and use an other variable to handle the selected value. – Polochon Nov 14 '16 at 16:01
  • @Polochon it's working but is there a way to make the others checked attribute false because if i do so it's making all the fields i press to true – Kokulan Nov 15 '16 at 02:02

2 Answers2

3

You need to add value:

@Component({
  selector: 'my-app',
  template: `
   <ul *ngFor="let data of list;">
    <li class="radio">
      <input type="radio" 
          [value]="data.value"
          name="sex" [(ngModel)]="user.sex">{{data.value}}
    </li>
</ul>
  `,
})
export class App {

  constructor() {
    this.user = {
      sex: 'One'
    }
    this.list= [{
      id: 1,
      value: 'One',
      checked: true
    },
      {
        id: 2,
        value: 'Two'
      }];
  }

}
2

I think what you need to is to create a field in the component to hold the selected value of the radio button group and add a two way binding to that value:

<ul>
    <li *ngFor="let data of list">
        <input type="radio"
               [value]="data.value"
               name="sex" [(ngModel)]="selectedValue" />
    </li>
</ul>

{{selectedValue}}


export class App {
selectedValue:string;
list= [{
      id: 1,
      value: 'One'
    },
      {
        id: 2,
        value: 'Two'
      }];
}
Kamal Saad
  • 167
  • 4