简体   繁体   English

使用复选框更改ngModel值

[英]change ngModel value with checkbox

good day .. I have this code and I need to send the role..but when I select the checkbox the ngModel changes to True or False and it is what is sent to the DB..How can I solve it? 美好的一天..我有这段代码,我需要发送角色。.但是当我选中复选框时,ngModel更改为True或False,这就是发送给数据库的内容。我该如何解决呢?

<mdl-checkbox class="mdl-textfield--full-width" *ngFor="let role of roles; let i = index"
[(ngModel)]="user.roles[i] " name="ckb{{i}}">
{{role.name}}
</mdl-checkbox>

Hard to say with only template. 仅凭模板很难说。 But it might be that you are overwriting the data if you are sending user, since you are using [(ngModel)]="user.roles[i]" on your checkbox, you are altering that value by clicking on the checkbox. 但是,如果您要发送用户,则可能是您覆盖了数据,因为您在复选框上使用了[(ngModel)]="user.roles[i]" ,因此您可以通过单击复选框来更改该值。 You can create an item on the roles array by doing role.isChecked . 您可以通过执行role.isChecked在角色数组上创建一个项目。 Then you can store the checked state. 然后,您可以存储选中状态。

I would suggest altering your object. 我建议更改您的对象。

public class Role {
    id: number;
    name: string;
    enabled: boolean;
}

<mdl-checkbox class="mdl-textfield--full-width" *ngFor="let role of roles; let i = index" [(ngModel)]="user.roles[i].Enabled" name="ckb{{i}}">
    {{role.name}}
</mdl-checkbox>

May be you can set user roles in change event? 也许您可以在change事件中设置用户角色? Like (change)="userRoles[i] = role" A sample plunkr using Angular only: Like (change)="userRoles[i] = role"仅使用Angular的示例plunkr:

https://plnkr.co/edit/erIQNgk6u1JxOc6zCoHW?p=preview https://plnkr.co/edit/erIQNgk6u1JxOc6zCoHW?p=preview

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM