微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何将ng-select与其他项目绑定取决于过滤器

如何解决如何将ng-select与其他项目绑定取决于过滤器

我正在使用以下代码绑定formgroup中存在的ng-select。

html:

<p>Select multiple elements using paste</p>
 <div class="col-md-offset-2 col-md-4">  
             <select style="widht:300px;" [ngModel]="selectedSearchFilter" (ngModelChange)="onChange($event)" name="sel3">
              <option [ngValue]="i" *ngFor="let i of searchFilters">{{i.name}}</option>
            </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 [formGroupName]="i">  
              <div class="form-group" class="row cols-md-12">  
                <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>
              </div>
        </div>  
    </div>  
</div>  
<button class="btn btn-primary" type="button"
       (click)="onClearDataClick()">Clear Data</button>
  </form>
  {{selectedSearchFilter | 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 {

people: Person[] = [];
selectedPeople = [];

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];
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 { 

      this.dataService.getRecords(filterName)
        //.pipe(map(x => x.filter(y => !y.disabled)))
        .subscribe((res) => {
            this.people = res;
            
            //this.selectedPeople = [this.people[0].id,this.people[1].id];
        });

   return this.formBuilder.group({  
    searchCreteria: [''] 
   });  
  }  

  onPaste(event: ClipboardEvent,i:any) {
  let clipboardData = event.clipboardData;
  let pastedData = clipboardData.getData('text');
    // split using spaces
    //var queries = pastedData.split(/\s/);
    var queries = pastedData.split(/\r\n|\r|\n/);
    //console.log(queries);
    // iterate over each part and add to the selectedItems
    queries.forEach(q => {
     var cnt = this.people.find(i => i.name.toLowerCase() === q.toLowerCase());
      console.log(cnt);
     if(cnt != undefined)
     {
        const control = <FormArray>this.personalForm.controls.other;
        const controlData = control.get([i]);
        controlData.get('isPointChecked').setValue(true);
        this.people[i]['isPointChecked'] = true;
    }});
   }
   onClearDataClick() {
    this.personalForm.reset();
  }
 onChange(e)
 {
  if(e.id != -1)
  {
   var cnt = this.ngSelectCount.find(i => i === e.id);
     if(cnt == undefined)
     {
       console.log(e.id);
      (<FormArray>this.personalForm.get('other')).push(this.addOtherSkillFormGroup(e.name));  
        this.ngSelectCount.push(e.id);
        this.selectedSearchFilter = e;
     }
  }
  else
  {
    this.personalForm.reset();
    this.ngSelectCount.length = 0;
   }
}

resetSearchCreteria(e)
{
  const index: number = this.ngSelectCount.indexOf(e);
  if (index !== -1) {
    this.ngSelectCount.splice(index,1);
  } 
}
/////////////////////////////

}

data.service.ts:

import { Injectable } from '@angular/core';
import { Observable,of } from 'rxjs';
import { delay,map } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';

export interface Person {
id: any;
name: string;
}

@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient) { }
getRecords(term: string = null): Observable<Person[]> {
    let items = this.getData(term);
    return of(items).pipe(delay(200));
}

getData(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" },name: "State 2" },name: "State 3" },name: "State 4" },name: "State 5" },name: "State 6" },name: "State 7" },name: "State 8" },name: "State 9" }
  ];
} else {
  return [
    { id: 1,name: "City 1" },name: "City 2" },name: "City 3" },name: "City 4" },name: "City 5" },name: "City 6" },name: "City 7" },name: "City 8" },name: "City 9" }
  ];
  }
}
}

在上面的代码中,我试图根据下拉列表选择绑定不同的项目。就像如果用户选择“国家/地区”,则国家/地区将使用ng-select绑定,如果州/省将选择,则各州将被绑定。但就我而言,最后的选择反映了所有的窗体控件。

完整的工作示例,您可以找到here

请帮助我配置这种情况。

解决方法

我不为什么我的答案标记为已删除。我花了很多时间进行此演示,您正在删除带有任何评论的帖子。

经过大量的研发并阅读了不同的教程。现在,我可以使用复制和粘贴选择多个项目。

有关实时示例,请检查以下链接Angular MultiSelect

感谢您的所有建议。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。