Angular 如何使用被动表单中的项目创建ng select

Angular 如何使用被动表单中的项目创建ng select,angular,angular-reactive-forms,angular-ngselect,Angular,Angular Reactive Forms,Angular Ngselect,我在不同的门户网站上搜索了很多,但还是没有成功。 如何在反应式表单中创建ng select。我想在反应式表单中创建以下html标记。以下代码段取自formGroup HTML: <ng-select #ngSelect formControlName="searchCreteria" [items]="people" [multiple]="true"

我在不同的门户网站上搜索了很多,但还是没有成功。 如何在反应式表单中创建ng select。我想在反应式表单中创建以下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>
<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}}
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" }
      ];
    }
  }
  /////////////////////////////
}

{{item.name |大写}}
原因:

 <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>
<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}}
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" }
      ];
    }
  }
  /////////////////////////////
}
我有一个搜索过滤器,根据下拉列表中选择的值,此ng select将与项目绑定。因此,在不同的下拉列表中,ng select将有不同的项。 例如,如果用户在下拉列表中选择国家,则会显示ng select formControl,并且所有国家都具有约束力。同样,if将根据下拉选择而变化


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

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

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>
<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}}
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" }
      ];
    }
  }
  /////////////////////////////
}
使用粘贴选择多个元素


{{other.controls.filterName.value} {{item.name |大写}} 清晰数据
显示所选项目 {{finalValues | json}}
TS:

 <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>
<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}}
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" }
      ];
    }
  }
  /////////////////////////////
}
从“@angular/core”导入{Component,OnInit,ViewChildren,ElementRef};
从“./data.service”导入{DataService,Person};
从“rxjs/operators”导入{map};
进口{
FormGroup,
形式上,
FormControl,
造模工,
验证器
}从“@angular/forms”;
@组成部分({
选择器:“多复选框示例”,
templateUrl:“./multi-checkbox-example.component.html”
})
导出类MultiCheckBox示例组件实现OnInit{
selectedSearchCreteria=[];
ngSelectCount=[];
个人形式:FormGroup;
搜索筛选器=[
{name:“--请选择项--”,id:-1},
{姓名:“国家”,id:1},
{姓名:“国家”,id:2},
{姓名:“城市”,id:3}
];
selectedSearchFilter=this.searchFilters[0].id;
建造师(
私有数据服务:数据服务,
私有表单生成器:表单生成器
) {}
恩戈尼尼特(){
this.personalForm=this.formBuilder.group({
过滤器:新FormControl(null),
其他:this.formBuilder.array([])
});
}
addOtherSkillFormGroup(过滤器名称:字符串):FormGroup{
让data=this.getDropData(filterName);
设groupData={
过滤器名称:[过滤器名称],
searchCreteria:[“”],
数据:[数据]
};
//groupData['data']=数据;
返回此.formBuilder.group(groupData);
}
onPaste(事件:剪贴簿事件,控制数据:任意,i:任意){
让clipboardData=event.clipboardData;
让pastedData=clipboardData.getData(“文本”);
//使用新行拆分
var querys=pastedData.split(/\r\n |\r |\n/);
//迭代每个部分并添加到selectedItems
querys.forEach(q=>{
var cnt=controlData.value.data.find(
i=>i.name.toLowerCase()==q.trim().toLowerCase()
);
如果(cnt!=未定义){
this.selectedSearchCreteria[i]=[…this.selectedSearchCreteria[i],cnt.id];
}
});
let节点:NodeListOf=document.queryselectoral(
“.ng输入”
)作为诺德利斯托夫;
for(设i=0;节点[i];i++){
(节点[i]作为HTMLElement.blur();
}
}
onClearDataClick(){
(this.personalForm.get(“其他”)).clear();
this.ngSelectCount.length=0;
this.selectedSearchFilter=this.searchFilters[0].id;
this.selectedSearchCreteria.length=0;
}
onChange(e){
如果(e.id!=-1){
var cnt=this.ngSelectCount.find(i=>i==e.id);
if(cnt==未定义){
(this.personalForm.get(“其他”)).push(
this.addOtherSkillFormGroup(e.name)
);
此.selectedSearchCreteria.push([]);
这个.ngSelectCount.push(e.id);
this.selectedSearchFilter=e.id;
}
}否则{
(this.personalForm.get(“其他”)).clear();
this.ngSelectCount.length=0;
this.selectedSearchFilter=this.searchFilters[0].id;
this.selectedSearchCreteria.length=0;
}
}
拆卸完成面板(e){
(本.personalForm.get(“其他”)).removeAt(e);
这个.ngSelectCount.splice(e,1);
this.selectedSearchFilter=this.searchFilters[0].id;
此.selectedSearchCreteria.拼接(e,1);
}
onShowSelectedItemsClick(){
让输出:any=“”;
(this.personalForm.get(“其他”)).controls.forEach(函数(formControl){
formControl.value[“searchCreteria”].forEach(q=>{
var cnt=formControl.value.data.find(i=>i.id==q);
//log(formControl.value[“filterName”]+'--'+cnt.name);
output=output+formControl.value[“filterName”]+'-'+cnt.name+','
});
});
警报(输出);
}
getDropData(过滤器类型:字符串){
如果(过滤器类型==“国家”){
返回[
{id:1,名称:“印度”},
{id:2,姓名:“瑞士”},
{id:3,姓名:“挪威”},
{id:4,名称:“澳门”},
{id:5,姓名:“卡塔尔”},
{id:6,姓名:“爱尔兰”},
{id:7,姓名:“美国”},
{id:15,姓名:“联合王国”},
{id:21,姓名:“阿拉伯联合酋长国”}
];
}else if(过滤器类型==“状态”){
返回[
{id:1,名称:“state1”},
{id:2,名称:“state2”},
{id:3,名称:“州3”},
{id:4,名称:“州4”},
{id:5,名称:“州5”},
{id:6,名称:“州6”},
{id:7,名称:“州7”},
{id:15,名称:“国家8”},
{id:21,姓名:“国家9”}
];
}否则{
返回[
{id:1,名称:“城市1”},
{id:2,名称:“城市2”},
{id:3,名称:“城市3”},
{id:4,名称:“城市4”},
{id:5,名字:“城市5”},