简体   繁体   English

在ngFor Angular 2中的输入类型复选框上设置检查状态

[英]set checked status on input type checkbox in ngFor Angular 2

I have an angular 2 application, where i use a ngFor to handle an bunch of checkboxes. 我有一个angular 2应用程序,在这里我使用ngFor处理一堆复选框。 when i initialize this component i need to set the state of the checkbox based on weather an id excists in an array 当我初始化此组件时,我需要根据天气设置复选框的状态,一个id存在于数组中

<div *ngFor="let option of listOptionResponse.options" class="col-md-12">
        <div class="col-lg-12">
            {{option.headline}}
        </div>
        <div class="col-lg-2 col-md-2 ">
            <input type="checkbox" class="form-control"  (change)="ServiceAddOrRemove($event, option.id)" name="choose">
        </div>
    </div>

In the component i have an array and if the options.id exists in this array i wanna set it to true. 在组件中,我有一个数组,如果options.id存在于此数组中,我想将其设置为true。

I cannot think of a good way to do this, and i have been looking for some sort of init event to use, bu without luck. 我想不出一个好方法来做到这一点,而且我一直在寻找某种可以使用的初始化事件,但是没有运气。 (this has nothing to do whith the excisting (change) event) (与正在发生的(更改)事件无关)

I hope you can help, and thanks in advance 希望您能提供帮助,并在此先感谢

You can just bind to checked like 您可以像这样绑定到checked

<input type="checkbox" class="form-control"  (change)="ServiceAddOrRemove($event, option.id)" name="choose"  
    [checked]="ids.indexOf(option.id) != -1">

也许您可以尝试以下方法:

<input type="checkbox" [(ngModel)]="option.id" class="form-control"  (change)="ServiceAddOrRemove($event, option.id)" name="choose">

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

相关问题 如果选中复选框,则将一组输入字段设置为禁用 - Set a group of input fields to be disabled if a checkbox is checked 为什么选中输入类型复选框后,其行为有所不同? - Why does input type checkbox act differently when it's checked? 如何仅通过Css设置悬停时检查的输入状态? - how to set input status checked on hover only via Css? 禁用复选框后,复选框不保持选中状态 - Checkbox does not hold checked status after disabling the checkbox 如何在Angular2中动态设置* ngFor的值 - How to set value of *ngFor dynamically in Angular2 动态生成角度为2的输入字段类型并设置字段类型 - Dynamically generate input field type with angular 2 and set the type of the field Angular2:输入使用ngFor控制表单标记内的损失值 - Angular2: Input Controls losses value inside form tag with ngFor 选中第一组复选框后,输入提交将被禁用 - Input submit is undisabled after first group checkbox checked 选中复选框输入时,如何在另一个元素中选择div? - How to select a div inside another element when a checkbox input is checked? LocalStorage输入=无线电|| 复选框|| 选择&amp;&amp; show div if:在加载时检查 - LocalStorage input=radio || checkbox || select && show div if :checked on load
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM