【问题标题】:How to create ng-select with items in reactive forms如何使用反应形式的项目创建 ng-select
【发布时间】:2020-12-14 19:56:40
【问题描述】:

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

原因:

我有一个搜索过滤器,根据在下拉列表中选择的值,这个 ng-select 将与项目绑定。所以在不同的下拉值上,ng-select 会有不同的项目。 例如,如果用户在下拉列表中选择 Country,则 ng-select formControl 将显示所有国家/地区绑定。以同样的方式,如果将根据下拉选择而有所不同。

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

【问题讨论】:

  • 您是否尝试实现 groupBy 功能?
  • 对不起,我没有问你问题。我只是在创建搜索过滤器。
  • 我假设你有一个 serach 过滤器,选择一个过滤器会用过滤后的结果填充你的 ng-select 吗?
  • 是的,如果用户选择国家,那么国家将绑定等等。我在这里只是为了例如在下拉列表中获取静态条目。在实际场景中,下拉菜单将包含随机数量的项目。

标签: angular angular-reactive-forms angular-ngselect


【解决方案1】:

我正在使用下面的代码sn-p来解决这个问题:

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

【讨论】:

    【解决方案2】:

    我认为我没有整理这两个答案的声誉,但我发现这个问题及其两个答案都很有启发性:ng-select multi select checkbox with reactive forms in angular 6

    【讨论】:

      【解决方案3】:

      在反应形式的情况下, 可以为 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,
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-08
        • 2019-02-23
        • 2022-10-12
        • 2019-07-03
        • 2021-06-15
        相关资源
        最近更新 更多