I am using this autocomplete to be able to select more than one user.
When I select a user, I am storing the ids in a variable using the push. This push will help me keep the ids of all selected users.
If you select a user and then want to remove it, the push will contain that user's ID :(
Is there a way that if I delete a user, that user ID will not appear or be removed from the array fed by the push?
Where I store all the ID's
var a = (this.nameIdMap.get(event.option.viewValue));
this.allIDS.push(a);
var c = this.allIDS;
var b = c.filter(function(value, index){ return c.indexOf(value) == index });
console.log(b)
Code
remove(fruit: string): void {
const index = this.fruits.indexOf(fruit);
if (index >= 0) {
this.fruits.splice(index, 1);
}
}
selected(event: MatAutocompleteSelectedEvent): void {
var a = (this.nameIdMap.get(event.option.viewValue));
this.allIDS.push(a);
var c = this.allIDS;
var b = c.filter(function(value, index){ return c.indexOf(value) == index });
console.log(b)
this.fruits.push(event.option.viewValue);
this.fruitInput.nativeElement.value = '';
this.fruitCtrl.setValue(null);
}
private _filter(value: string): string[] {
const filterValue = value.toLowerCase();
return this.allFruits.filter(fruit => fruit.toLowerCase().indexOf(filterValue) === 0);
}
<mat-form-field class="example-chip-list">
<mat-chip-list #chipList>
<mat-chip
*ngFor="let fruit of fruits"
[selectable]="selectable"
[removable]="removable"
(removed)="remove(fruit)">
{{fruit}}
<mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
</mat-chip>
<input
placeholder="New fruit..."
#fruitInput
[formControl]="fruitCtrl"
[matAutocomplete]="auto"
[matChipInputFor]="chipList"
[matChipInputSeparatorKeyCodes]="separatorKeysCodes"
[matChipInputAddOnBlur]="addOnBlur">
</mat-chip-list>
<mat-autocomplete #auto="matAutocomplete" (optionSelected)="selected($event)">
<mat-option *ngFor="let fruit of filteredFruits | async" [value]="fruit">
{{fruit}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
Problem
As you can see, I selected 3 users and then deleted 1. In total I have 2 users selected, but in the array I have the ids of the 2 selected users + the id of the eliminated user. This deleted user id should not be present :(
You simply to need to remove the same index from this.allIDs
as you do from this.fruits
remove(fruit: string): void {
const index = this.fruits.indexOf(fruit);
if (index >= 0) {
this.fruits.splice(index, 1);
this.allIDS.splice(index, 1);
}
}
Alternatively you could create an array of objects that holds the name and ID of each entry as one object.