ng-select multi select checkbox with reactive forms in angular 6

本秂侑毒 提交于 2021-01-26 07:30:21

问题


Please go through the link(https://ng-select.github.io/ng-select#/multiselect-checkbox) to know ng-select multi select checkbox.

I am trying to use the ng-select "Group selects children" in my angular 6 application.

I am having problem using ng-select "Group selects children" with Reactive Forms instead of template driven forms.

I have tired it as

<ng-select
          [items]="userGroupsList"
          [multiple]="true"
          bindLabel="name"
          groupBy="gender"
          [selectableGroup]="true"
          [selectableGroupAsModel]="false"
          [closeOnSelect]="false"
          bindValue="id"
          formControlName="userGroups" placeholder="Select a user group">
            <ng-template ng-optgroup-tmp let-item="item" let-item$="item$" let-index="index">
                <input id="item-{{index}}" type="checkbox" [(ngModel)]="" formControlName="userGroupParent"/> {{item.gender | uppercase}}
            </ng-template>
            <ng-template ng-option-tmp let-item="item" let-item$="item$" let-index="index">
                <input id="item-{{index}}" type="checkbox" [(ngModel)]="" formControlName="userGroupChild"/> {{item.name}}
            </ng-template>
        </ng-select>

I have used the same data of the multiselect-checkbox-- [items]="userGroupsList"

https://github.com/ng-select/ng-select/blob/master/demo/app/shared/data.service.ts -- getMockPeople() has the data

So here can i use the [(ngModel)] as well as formControlName on the input how can i child elements are selected when the parent is select as in the example

Please help....!


回答1:


To make this work with formGroup : keep the formControlName on the ng-select who will be bind to your formGroup.

The problem is those input in the template. For me the best solution is to keep using ngModel like in the example. But you must make angular understand that is as nothing to do with the fromGroup so you can add the option standalone on it.

<input id="item-{{index}}" type="checkbox" [(ngModel)]="item$.selected" [ngModelOptions]="{ standalone : true }" />



回答2:


There is an other way to do that without the ngModel :

<input id="item-{{index}}" type="checkbox" [checked]="item$.selected" /> 


来源:https://stackoverflow.com/questions/52411758/ng-select-multi-select-checkbox-with-reactive-forms-in-angular-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!