如何在 Angular 2+ 中预选和更新复选框 [英] How to pre-select and update checkboxes in Angular 2+

查看:30
本文介绍了如何在 Angular 2+ 中预选和更新复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Angular 中实现一个清单.必须根据 ts 文件中的数组预先检查某些框,并且在选中复选框时必须更新数组.我这样做:

<input type="checkbox" aria-label="Checkbox 1" [value]="option.text" name="checkBox" [(ngModel)]="optionsSelectedArray"/><label for='{{option.optionId}}'><span class="que">{{option.text}}</span></label>

optionsSelectedArray 包含从服务器检索的选项 ID.

但它不起作用.呈现分区时,所有复选框都会被选中.

编辑

我已将代码更改如下:

<input type="checkbox" id="{{option.optionId}}" name="checkBox" [(ngModel)]="option.userResponse" (ngModelChange)="setResponseChanged()"><label for='{{option.optionId}}'><span class="que">{{option.text}}</span></label>

这里 option.userResponse 是布尔值.现在在选择复选框时,currentQuestion 对象正在正确更改,但是当清单第一次加载时,复选框未正确选中.如果 option.userResponse 最后一次为真,则选中所有复选框item ,否则没有检查.

解决方案

也许这可以满足您的需求

<input type="checkbox" aria-label="Checkbox 1" name="checkBox" [(ngModel)]="optionsSelectedArray[i]"/><label for='{{option.optionId}}'><span class="que">{{option.text}}</span></label>

(我添加了 ; let i=index[i])

I want to implement a checklist in Angular. Some boxes have to be pre-checked based on an array in the ts file and the array has to be updated when a checkbox is checked. I am doing it like:

<div class='form-group que-box' *ngFor="let option of currentQuestion.options">
  <input type="checkbox" aria-label="Checkbox 1" [value]="option.text" name="checkBox" [(ngModel)]="optionsSelectedArray"/>
  <label for='{{option.optionId}}'><span class="que">{{option.text}}</span></label>
</div>

optionsSelectedArray contains the option IDs retrieved from server.

But it doesn't work. All the checkboxes come checked when the the division is rendered.

EDIT

I have changed my code as follows :

<div class='form-group que-box' *ngFor="let option of currentQuestion.options">
  <input type="checkbox" id="{{option.optionId}}" name="checkBox" [(ngModel)]="option.userResponse" (ngModelChange)= "setResponseChanged()">
  <label for='{{option.optionId}}'><span class="que">{{option.text}}</span></label>
</div>

Here option.userResponse in boolean. Now on selecting the checkboxes the currentQuestion object is correctly changing but when the checklist loads for the first time, the checkboxes are not checked correctly.All the checkboxes come checked if the option.userResponse is true for the last item ,none come checked otherwise.

解决方案

Perhaps this might do what you want

<div class='form-group que-box' *ngFor="let option of currentQuestion.options; let i=index">
  <input type="checkbox" aria-label="Checkbox 1" name="checkBox" [(ngModel)]="optionsSelectedArray[i]"/>
  <label for='{{option.optionId}}'><span class="que">{{option.text}}</span></label>
</div>

(I added ; let i=index and [i])

这篇关于如何在 Angular 2+ 中预选和更新复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆