I am using following code to bind ng-select present in formgroup.
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" },
{ 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" }
];
}
}
}
In above code, I am trying to bind different items on basis of dropdown selection. Like if user select Country then countries will be bind with ng-select and if states will select then states will be bind. But in my case last selection is reflecting for all formcontroles.
Complete working sample you can find here
Could you please help me to configure this case.
I don't why my answer marked as deleted. I spent lots of time make this demo and you are deleting post with any comment.
After doing lots of R&D and reading different tutorials. Now, I am able to select multiple items using copy&paste.
For live example please check following link Angular MultiSelect
Thanks for all your suggestions.