[英]angular2 two way binding for radio button
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 但它不起作用我想单击单选按钮时动态更新检查的变量
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'
}];
}
}
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'
}];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.