angular2 two way binding for radio button

kohli picture kohli · Nov 14, 2016 · Viewed 7k times · Source

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

Answer

user7122183 picture user7122183 · Nov 14, 2016

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

}