Search code examples
angularangular-reactive-formsangular-ngselect

How to create ng-select with items in reactive forms


I searched a lot on different web portals on this, but still I didn't get any success. How we can create ng-select in reactive forms.I want to create following html tag with in reactive form. Following code snippet is taken from formGroup.

HTML:

 <ng-select #ngSelect formControlName="searchCreteria"
                    [items]="people"
                    [multiple]="true"
                     bindLabel="name"
                    [closeOnSelect]="false"
                    [clearSearchOnAdd]="true"
                     bindValue="id"
                    (paste)="onPaste($event,i)"
                    (clear)="resetSearchCreteria(item)"
                    [selectOnTab]="true"
                    [closeOnSelect]="true">
                    <ng-template ng-option-tmp let-item="item" let-item$="item$" let-index="index">
                        <input id="item-{{index}}" type="checkbox"/> {{item.name | uppercase}}
                    </ng-template>
                </ng-select>

Reason:

I have one search filter, where on the basis on value selected in dropdown this ng-select will bind with items. So on different dropdown values ng-select will have different items. For example, If user selecting Country in dropdown then ng-select formControl will be appear with all countries binding. In same way if will vary as per dropdown selection.

Please let me know if you need more detail, I will try to provide.


Solution

  • I am using the following code snippet to solve this issue:

    HTML:

    <p>Select multiple elements using paste</p>
    <div class="col-md-offset-2 col-md-4">
    <!-- <select style="width:200px;" [ngModel]="selectedSearchFilter" (ngModelChange)="onChange($event)" name="sel3">
                  <option [ngValue]="i" *ngFor="let i of searchFilters">{{i.name}}</option>
                </select> -->
        <ng-select style="width:300px;" [items]="searchFilters"
        [clearable]="false"
                                               bindLabel="name"
                                               bindValue="id"
                                               [(ngModel)]="selectedSearchFilter"
                                               (change)="onChange($event)">
                                    </ng-select>         
        </div>
          <br>
    
       <form class="form-horizontal" [formGroup]="personalForm" (ngSubmit)="onSubmit()">
        <div style="background-color: gainsboro">
        <div formArrayName="other" *ngFor="let other of personalForm.get('other').controls; let i = index"
            class="form-group"> 
     
            <div [formGroup]="other">
                <div class="form-group" class="row cols-md-12">
           <span for="filterName">{{other.controls.filterName.value}}</span>
                    <ng-select #ngSelect formControlName="searchCreteria" 
          [items]="other.value.data" 
          [multiple]="true"
          [virtualScroll]="true"
                        bindLabel="name" 
            [closeOnSelect]="false" 
            [clearSearchOnAdd]="true"
             bindValue="id"
                        (paste)="onPaste($event,other,i)" 
            (clear)="removeCompletePanel(i)" 
            [selectOnTab]="true"
                        [closeOnSelect]="true" [(ngModel)]="selectedSearchCreteria[i]">
                        <!-- <ng-template ng-option-tmp let-item="item" let-item$="item$" let-index="index">
                            <input [ngModelOptions]="{standalone: true}" [ngModel]="item$.selected" id="item-{{index}}" type="checkbox"/> {{item.name | uppercase}}
            </ng-template> -->
                <ng-template ng-option-tmp let-item="item" let-index="index">
                            <input [ngModelOptions]="{standalone: true}" [ngModel]="item.selected" id="item-{{index}}" type="checkbox"/> {{item.name | uppercase}}
            </ng-template>
                    </ng-select>
                </div>
            </div>
        </div>
    </div>
    <button class="btn btn-primary" type="button"
           (click)="onClearDataClick()">Clear Data</button>
    <br>
    <button class="btn btn-primary" type="button"
           (click)="onShowSelectedItemsClick()">Show Selected items</button>
    </form>
    
    {{finalValues | json}}
    

    TS:

    import { Component, OnInit, ViewChildren, ElementRef } from "@angular/core";
    import { DataService, Person } from "../data.service";
    import { map } from "rxjs/operators";
    import {
      FormGroup,
      FormArray,
      FormControl,
      FormBuilder,
      Validators
    } from "@angular/forms";
    
    @Component({
      selector: "multi-checkbox-example",
      templateUrl: "./multi-checkbox-example.component.html"
    })
    export class MultiCheckboxExampleComponent implements OnInit {
     
      selectedSearchCreteria = [];
      ngSelectCount = [];
      personalForm: FormGroup;
    
      searchFilters = [
        { name: "--Please Select Item--", id: -1 },
        { name: "Country", id: 1 },
        { name: "States", id: 2 },
        { name: "Cities", id: 3 }
      ];
      selectedSearchFilter = this.searchFilters[0].id;
    
      constructor(
        private dataService: DataService,
        private formBuilder: FormBuilder
      ) {}
    
      ngOnInit() {
        this.personalForm = this.formBuilder.group({
          filter: new FormControl(null),
          other: this.formBuilder.array([])
        });
      }
    
      addOtherSkillFormGroup(filterName: string): FormGroup {
        let data = this.getDropData(filterName);
        let groupData = {
          filterName:[filterName],
          searchCreteria: [""],
          data: [data]
        };
        //groupData['data']=data;
        return this.formBuilder.group(groupData);
      }
    
      onPaste(event: ClipboardEvent, controlData: any, i: any) {
        let clipboardData = event.clipboardData;
        let pastedData = clipboardData.getData("text");
        // split using new line
        var queries = pastedData.split(/\r\n|\r|\n/);
        // iterate over each part and add to the selectedItems
        queries.forEach(q => {
          var cnt = controlData.value.data.find(
            i => i.name.toLowerCase() === q.trim().toLowerCase()
          );
          if (cnt != undefined) {
            this.selectedSearchCreteria[i] = [...this.selectedSearchCreteria[i], cnt.id];
          }
        });
        let nodes: NodeListOf<HTMLElement> = document.querySelectorAll(
          ".ng-input input"
        ) as NodeListOf<HTMLElement>;
        for (let i = 0; nodes[i]; i++) {
          (nodes[i] as HTMLElement).blur();
        }
      }
    
      onClearDataClick() {
        (<FormArray>this.personalForm.get("other")).clear();
        this.ngSelectCount.length = 0;
        this.selectedSearchFilter = this.searchFilters[0].id;
        this.selectedSearchCreteria.length = 0;
      }
      onChange(e) {
        if (e.id != -1) {
          var cnt = this.ngSelectCount.find(i => i === e.id);
          if (cnt == undefined) {
            (<FormArray>this.personalForm.get("other")).push(
              this.addOtherSkillFormGroup(e.name)
            );
            this.selectedSearchCreteria.push([]);
            this.ngSelectCount.push(e.id);
            this.selectedSearchFilter = e.id;
          }
        } else {
          (<FormArray>this.personalForm.get("other")).clear();
          this.ngSelectCount.length = 0;
          this.selectedSearchFilter = this.searchFilters[0].id;
          this.selectedSearchCreteria.length = 0;
        }
      }
    
      removeCompletePanel(e) {
        (<FormArray>this.personalForm.get("other")).removeAt(e);
        this.ngSelectCount.splice(e, 1);
        this.selectedSearchFilter = this.searchFilters[0].id;
        this.selectedSearchCreteria.splice(e, 1);
      }
    
      onShowSelectedItemsClick() {
        let output:any = "";
        (<FormArray>this.personalForm.get("other")).controls.forEach(function(formControl) {
          formControl.value["searchCreteria"].forEach(q => {
            var cnt = formControl.value.data.find(i => i.id === q);
            //console.log(formControl.value["filterName"]+'--'+cnt.name);
            output = output + formControl.value["filterName"]+'--'+cnt.name+','
          });
        });
        alert(output);
      }
    
      getDropData(filterType: string) {
        if (filterType == "Country") {
          return [
            { id: 1, name: "India" },
            { id: 2, name: "Switzerland" },
            { id: 3, name: "Norway" },
            { id: 4, name: "Macao" },
            { id: 5, name: "Qatar" },
            { id: 6, name: "Ireland" },
            { id: 7, name: "United States" },
            { id: 15, name: "United Kingdom" },
            { id: 21, name: "United Arab Emirates" }
          ];
        } else if (filterType == "States") {
          return [
            { id: 1, name: "State 1" },
            { id: 2, name: "State 2" },
            { id: 3, name: "State 3" },
            { id: 4, name: "State 4" },
            { id: 5, name: "State 5" },
            { id: 6, name: "State 6" },
            { id: 7, name: "State 7" },
            { id: 15, name: "State 8" },
            { id: 21, name: "State 9" }
          ];
        } else {
          return [
            { id: 1, name: "City 1" },
            { id: 2, name: "City 2" },
            { id: 3, name: "City 3" },
            { id: 4, name: "City 4" },
            { id: 5, name: "City 5" },
            { id: 6, name: "City 6" },
            { id: 7, name: "City 7" },
            { id: 15, name: "City 8" },
            { id: 21, name: "City 9" }
          ];
        }
      }
      /////////////////////////////
    }