如何使用反应形式的项目创建 ng-select

How to create ng-select with items in reactive forms

我在不同的门户网站上搜索了很多,但仍然没有得到任何成功。 我们如何在反应式中创建 ng-select forms.I 想要以反应式形式创建以下 html 标签。以下代码片段取自 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>

原因:

我有一个搜索过滤器,根据在下拉列表中输入的值 select,此 ng-select 将与项目绑定。所以在不同的下拉值上 ng-select 会有不同的项目。 例如,如果用户 selecting Country 在下拉列表中,那么 ng-select formControl 将出现所有国家绑定。以同样的方式,如果会根据下拉列表 selection.

如果您需要更多详细信息,请告诉我,我会尽力提供。

我正在使用以下代码片段来解决这个问题:

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" }
      ];
    }
  }
  /////////////////////////////
}

我认为我没有整理这两个答案的名声,但我发现这个问题及其两个答案都具有启发性:

在反应形式的情况下, 可以使用 FormGroup 的 patchValue 内置函数。

示例: HTML:

<form [formGroup]="learnerForm"> 
    <ng-select
        [items]="managerList$ | async"
        bindValue="id"
        bindLabel="email"
        placeholder="Manager"
        formControlName="manager">
    </ng-select> 
</form>

TS:

this.learnerForm.patchValue({
    manager: updatedID,
});