kittencup / angular2-ama-cn

angular2 随便问
692 stars 101 forks source link

单选框双向绑定问题 #250

Open pluscao opened 7 years ago

pluscao commented 7 years ago

选择性别的单选框如何双向绑定到用户数据user.sex上?


hstarorg commented 7 years ago
<input type="radio" value="male" name="sex" [(ngModel)]="user.sex">
<input type="radio" value="female" name="sex" [(ngModel)]="user.sex">
pluscao commented 7 years ago

这样的话[checked]="user.sex"会失效,为什么呢? 我用下面的方式做是可以提交到数据库的,但是用[(ngModel)]就无论无何都提交不进去。。。。。。。。。。数据库那边使用boolean类型存储的

<label >sex:
      <label> male
      <input type="radio" [checked]="user.sex == true" name="sex" #male (click)="sex(true)"></label>
      <label>female
      <input type="radio" [checked]="user.sex == false" name="sex"  #female (click)="sex(false)" ></label>
    </label><br>

/////////////////////////////////////////////////////////////////////// sex(flag: boolean){ this.user.sex = flag; }

hstarorg commented 7 years ago

ngModel能取到值,肯定是能提交进去的。

pluscao commented 7 years ago

那checked失效该怎么办呐。。。?

hstarorg commented 7 years ago

根据就不需要这个玩意。

pluscao commented 7 years ago

image image 但是这样的话一开始就没有值了。。。。。怎么办,好纠结

hstarorg commented 7 years ago

把user.sex 设置为 true 或者 false,就能选中一个呢。

pluscao commented 7 years ago

是后台数据类型的原因,谢谢了啊。。