简体   繁体   中英

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. when i initialize this component i need to set the state of the checkbox based on weather an id excists in an array

<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.

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

<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">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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