这是我的代码,在姓氏中,我使用了ngModel,因此它使用了双向数据绑定,但在单选按钮中我是如何使用ngModel进行双向数据绑定的。
<div class="form-group" [ngClass]="{ 'has-error': f.submitted && !lastname.valid }">
<label for="lastname">Last Name</label>
<input type="text" class="form-control" name="last_name" [(ngModel)]="employee.last_name" #lastname="ngModel" required />
<div *ngIf="f.submitted && !lastname.valid" class="help-block">Last Name is required</div>
</div>
<div class="form-group">
<label>Gender:</label>
<label class="radio-inline">
<input type="radio" name="optradio" [checked]="employee.gender == 'Male'" >Male
</label>
<label class="radio-inline">
<input type="radio" name="optradio" [checked]="employee.gender == 'Female'" >Female
</label>
</div>
答案 0 :(得分:5)
对于双向数据绑定,它与所有其他数据绑定一样使用此语法[(ngModel)]
用以下内容替换您的代码块:
<div class="form-group">
<label>Gender:</label>
<label class="radio-inline">
<input type="radio" name="optradio" value='Male' [(ngModel)]="employee.gender" >Male
</label>
<label class="radio-inline">
<input type="radio" name="optradio" value='Female' [(ngModel)]="employee.gender" >Female
</label>
</div>
答案 1 :(得分:1)
你可以试试这个
<div class="form-group">
<label>Gender:</label>
<label class="radio-inline">
<input type="radio" name="gender" [(ngModel)]="employee.gender"
[value]='Male' [checked]="employee.gender == 'Male'" >Male
</label>
<label class="radio-inline">
<input type="radio" name="gender" [(ngModel)]="employee.gender"
[value]='Female' [checked]="employee.gender == 'Female'" >Female
</label>
</div>
此外,您忘记在输入中添加[value]
属性,并将name
的{{1}}更改为input