Angular Material=> Mat-chip- Autocomplete(input) on selecting dropdown through space key
How to populate mat-chip onkeypress(spacebar) when we select mat-option by going on option through arrow key and pressing space key(32).
However, it is working fine when we select dropdownmenu by going to option through arrowkey and then pressing enter key(keycode- 13) but not working on similarly on space key(keycode -32).
Here, is stackblitz link:-
https://stackblitz.com/edit/angular-ytk8qk-feaqaw?file=app/chips-autocomplete-example.html
1) How to add select dropdown option by going through
arrowkey(not mouse) and populating selected option using spacebar(keycode- 32).
2)How to remove option from dropdown that is already populated or used.
3)Show dropdown only when user enters some charcter in input text else show
class="info"` text only in dropdown, when no input text is there and no
option in dropdown matches enter charcters in input.
Note:- The user can create chips by typing in input and then press ENTER or SPACE key (separator key) for creating chips.
chip.component.ts
export class ChipsAutocompleteExample {
visible = true;
selectable = true;
removable = true;
addOnBlur = true;
separatorKeysCodes: number = [ENTER,SPACE, COMMA];
fruitCtrl = new FormControl();
filteredFruits: Observable<string>;
fruits: string = ['Lemon'];
allFruits: string = ['Apple', 'Lemon', 'Lime', 'Orange', 'Strawberry'];
@ViewChild('fruitInput') fruitInput: ElementRef<HTMLInputElement>;
@ViewChild('auto') matAutocomplete: MatAutocomplete;
constructor() {
this.filteredFruits = this.fruitCtrl.valueChanges.pipe(
startWith(null),
map((fruit: string | null) => fruit ? this._filter(fruit) : this.allFruits.slice()));
}
add(event: MatChipInputEvent): void {
// Add fruit only when MatAutocomplete is not open
// To make sure this does not conflict with OptionSelected Event
if (!this.matAutocomplete.isOpen) {
const input = event.input;
const value = event.value;
// Add our fruit
if ((value || '').trim()) {
this.fruits.push(value.trim());
}
// Reset the input value
if (input) {
input.value = '';
}
this.fruitCtrl.setValue(null);
}
}
remove(fruit: string): void {
const index = this.fruits.indexOf(fruit);
if (index >= 0) {
this.fruits.splice(index, 1);
}
}
selected(event: MatAutocompleteSelectedEvent): void {
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);
}
}
|
show 1 more comment
How to populate mat-chip onkeypress(spacebar) when we select mat-option by going on option through arrow key and pressing space key(32).
However, it is working fine when we select dropdownmenu by going to option through arrowkey and then pressing enter key(keycode- 13) but not working on similarly on space key(keycode -32).
Here, is stackblitz link:-
https://stackblitz.com/edit/angular-ytk8qk-feaqaw?file=app/chips-autocomplete-example.html
1) How to add select dropdown option by going through
arrowkey(not mouse) and populating selected option using spacebar(keycode- 32).
2)How to remove option from dropdown that is already populated or used.
3)Show dropdown only when user enters some charcter in input text else show
class="info"` text only in dropdown, when no input text is there and no
option in dropdown matches enter charcters in input.
Note:- The user can create chips by typing in input and then press ENTER or SPACE key (separator key) for creating chips.
chip.component.ts
export class ChipsAutocompleteExample {
visible = true;
selectable = true;
removable = true;
addOnBlur = true;
separatorKeysCodes: number = [ENTER,SPACE, COMMA];
fruitCtrl = new FormControl();
filteredFruits: Observable<string>;
fruits: string = ['Lemon'];
allFruits: string = ['Apple', 'Lemon', 'Lime', 'Orange', 'Strawberry'];
@ViewChild('fruitInput') fruitInput: ElementRef<HTMLInputElement>;
@ViewChild('auto') matAutocomplete: MatAutocomplete;
constructor() {
this.filteredFruits = this.fruitCtrl.valueChanges.pipe(
startWith(null),
map((fruit: string | null) => fruit ? this._filter(fruit) : this.allFruits.slice()));
}
add(event: MatChipInputEvent): void {
// Add fruit only when MatAutocomplete is not open
// To make sure this does not conflict with OptionSelected Event
if (!this.matAutocomplete.isOpen) {
const input = event.input;
const value = event.value;
// Add our fruit
if ((value || '').trim()) {
this.fruits.push(value.trim());
}
// Reset the input value
if (input) {
input.value = '';
}
this.fruitCtrl.setValue(null);
}
}
remove(fruit: string): void {
const index = this.fruits.indexOf(fruit);
if (index >= 0) {
this.fruits.splice(index, 1);
}
}
selected(event: MatAutocompleteSelectedEvent): void {
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);
}
}
It seems that if the list component is focused, space key works the same as enter. On the stackblitz you provided, I tried inspecting one of the elements of the list, then returned to the list, pressed space key and it was selected. Maybe knowing this may help you implement what you're looking for.
– GCSDC
Nov 28 '18 at 20:09
Its not working. You don't have to use mouse to open dropdown. When input is focus just use arrow key to select a particular option and click space key to select that option. However, enter key is working.
– Mahi
Nov 28 '18 at 20:14
Have you reviewed this? space doesn't seem to be an option for autocomplete material.angular.io/components/autocomplete/…
– Marshal
Nov 28 '18 at 20:41
Thanks, Keyboard interaction DOWN_ARROW: Next option becomes active.UP_ARROW: Previous option becomes active.ENTER: Select currently active item.
– Mahi
Nov 28 '18 at 20:46
But, it can also be selected using space key. That is requirement
– Mahi
Nov 28 '18 at 20:47
|
show 1 more comment
How to populate mat-chip onkeypress(spacebar) when we select mat-option by going on option through arrow key and pressing space key(32).
However, it is working fine when we select dropdownmenu by going to option through arrowkey and then pressing enter key(keycode- 13) but not working on similarly on space key(keycode -32).
Here, is stackblitz link:-
https://stackblitz.com/edit/angular-ytk8qk-feaqaw?file=app/chips-autocomplete-example.html
1) How to add select dropdown option by going through
arrowkey(not mouse) and populating selected option using spacebar(keycode- 32).
2)How to remove option from dropdown that is already populated or used.
3)Show dropdown only when user enters some charcter in input text else show
class="info"` text only in dropdown, when no input text is there and no
option in dropdown matches enter charcters in input.
Note:- The user can create chips by typing in input and then press ENTER or SPACE key (separator key) for creating chips.
chip.component.ts
export class ChipsAutocompleteExample {
visible = true;
selectable = true;
removable = true;
addOnBlur = true;
separatorKeysCodes: number = [ENTER,SPACE, COMMA];
fruitCtrl = new FormControl();
filteredFruits: Observable<string>;
fruits: string = ['Lemon'];
allFruits: string = ['Apple', 'Lemon', 'Lime', 'Orange', 'Strawberry'];
@ViewChild('fruitInput') fruitInput: ElementRef<HTMLInputElement>;
@ViewChild('auto') matAutocomplete: MatAutocomplete;
constructor() {
this.filteredFruits = this.fruitCtrl.valueChanges.pipe(
startWith(null),
map((fruit: string | null) => fruit ? this._filter(fruit) : this.allFruits.slice()));
}
add(event: MatChipInputEvent): void {
// Add fruit only when MatAutocomplete is not open
// To make sure this does not conflict with OptionSelected Event
if (!this.matAutocomplete.isOpen) {
const input = event.input;
const value = event.value;
// Add our fruit
if ((value || '').trim()) {
this.fruits.push(value.trim());
}
// Reset the input value
if (input) {
input.value = '';
}
this.fruitCtrl.setValue(null);
}
}
remove(fruit: string): void {
const index = this.fruits.indexOf(fruit);
if (index >= 0) {
this.fruits.splice(index, 1);
}
}
selected(event: MatAutocompleteSelectedEvent): void {
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);
}
}
How to populate mat-chip onkeypress(spacebar) when we select mat-option by going on option through arrow key and pressing space key(32).
However, it is working fine when we select dropdownmenu by going to option through arrowkey and then pressing enter key(keycode- 13) but not working on similarly on space key(keycode -32).
Here, is stackblitz link:-
https://stackblitz.com/edit/angular-ytk8qk-feaqaw?file=app/chips-autocomplete-example.html
1) How to add select dropdown option by going through
arrowkey(not mouse) and populating selected option using spacebar(keycode- 32).
2)How to remove option from dropdown that is already populated or used.
3)Show dropdown only when user enters some charcter in input text else show
class="info"` text only in dropdown, when no input text is there and no
option in dropdown matches enter charcters in input.
Note:- The user can create chips by typing in input and then press ENTER or SPACE key (separator key) for creating chips.
chip.component.ts
export class ChipsAutocompleteExample {
visible = true;
selectable = true;
removable = true;
addOnBlur = true;
separatorKeysCodes: number = [ENTER,SPACE, COMMA];
fruitCtrl = new FormControl();
filteredFruits: Observable<string>;
fruits: string = ['Lemon'];
allFruits: string = ['Apple', 'Lemon', 'Lime', 'Orange', 'Strawberry'];
@ViewChild('fruitInput') fruitInput: ElementRef<HTMLInputElement>;
@ViewChild('auto') matAutocomplete: MatAutocomplete;
constructor() {
this.filteredFruits = this.fruitCtrl.valueChanges.pipe(
startWith(null),
map((fruit: string | null) => fruit ? this._filter(fruit) : this.allFruits.slice()));
}
add(event: MatChipInputEvent): void {
// Add fruit only when MatAutocomplete is not open
// To make sure this does not conflict with OptionSelected Event
if (!this.matAutocomplete.isOpen) {
const input = event.input;
const value = event.value;
// Add our fruit
if ((value || '').trim()) {
this.fruits.push(value.trim());
}
// Reset the input value
if (input) {
input.value = '';
}
this.fruitCtrl.setValue(null);
}
}
remove(fruit: string): void {
const index = this.fruits.indexOf(fruit);
if (index >= 0) {
this.fruits.splice(index, 1);
}
}
selected(event: MatAutocompleteSelectedEvent): void {
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);
}
}
edited Nov 29 '18 at 8:16
Mahi
asked Nov 28 '18 at 18:24
MahiMahi
783421
783421
It seems that if the list component is focused, space key works the same as enter. On the stackblitz you provided, I tried inspecting one of the elements of the list, then returned to the list, pressed space key and it was selected. Maybe knowing this may help you implement what you're looking for.
– GCSDC
Nov 28 '18 at 20:09
Its not working. You don't have to use mouse to open dropdown. When input is focus just use arrow key to select a particular option and click space key to select that option. However, enter key is working.
– Mahi
Nov 28 '18 at 20:14
Have you reviewed this? space doesn't seem to be an option for autocomplete material.angular.io/components/autocomplete/…
– Marshal
Nov 28 '18 at 20:41
Thanks, Keyboard interaction DOWN_ARROW: Next option becomes active.UP_ARROW: Previous option becomes active.ENTER: Select currently active item.
– Mahi
Nov 28 '18 at 20:46
But, it can also be selected using space key. That is requirement
– Mahi
Nov 28 '18 at 20:47
|
show 1 more comment
It seems that if the list component is focused, space key works the same as enter. On the stackblitz you provided, I tried inspecting one of the elements of the list, then returned to the list, pressed space key and it was selected. Maybe knowing this may help you implement what you're looking for.
– GCSDC
Nov 28 '18 at 20:09
Its not working. You don't have to use mouse to open dropdown. When input is focus just use arrow key to select a particular option and click space key to select that option. However, enter key is working.
– Mahi
Nov 28 '18 at 20:14
Have you reviewed this? space doesn't seem to be an option for autocomplete material.angular.io/components/autocomplete/…
– Marshal
Nov 28 '18 at 20:41
Thanks, Keyboard interaction DOWN_ARROW: Next option becomes active.UP_ARROW: Previous option becomes active.ENTER: Select currently active item.
– Mahi
Nov 28 '18 at 20:46
But, it can also be selected using space key. That is requirement
– Mahi
Nov 28 '18 at 20:47
It seems that if the list component is focused, space key works the same as enter. On the stackblitz you provided, I tried inspecting one of the elements of the list, then returned to the list, pressed space key and it was selected. Maybe knowing this may help you implement what you're looking for.
– GCSDC
Nov 28 '18 at 20:09
It seems that if the list component is focused, space key works the same as enter. On the stackblitz you provided, I tried inspecting one of the elements of the list, then returned to the list, pressed space key and it was selected. Maybe knowing this may help you implement what you're looking for.
– GCSDC
Nov 28 '18 at 20:09
Its not working. You don't have to use mouse to open dropdown. When input is focus just use arrow key to select a particular option and click space key to select that option. However, enter key is working.
– Mahi
Nov 28 '18 at 20:14
Its not working. You don't have to use mouse to open dropdown. When input is focus just use arrow key to select a particular option and click space key to select that option. However, enter key is working.
– Mahi
Nov 28 '18 at 20:14
Have you reviewed this? space doesn't seem to be an option for autocomplete material.angular.io/components/autocomplete/…
– Marshal
Nov 28 '18 at 20:41
Have you reviewed this? space doesn't seem to be an option for autocomplete material.angular.io/components/autocomplete/…
– Marshal
Nov 28 '18 at 20:41
Thanks, Keyboard interaction DOWN_ARROW: Next option becomes active.UP_ARROW: Previous option becomes active.ENTER: Select currently active item.
– Mahi
Nov 28 '18 at 20:46
Thanks, Keyboard interaction DOWN_ARROW: Next option becomes active.UP_ARROW: Previous option becomes active.ENTER: Select currently active item.
– Mahi
Nov 28 '18 at 20:46
But, it can also be selected using space key. That is requirement
– Mahi
Nov 28 '18 at 20:47
But, it can also be selected using space key. That is requirement
– Mahi
Nov 28 '18 at 20:47
|
show 1 more comment
1 Answer
1
active
oldest
votes
1) How to add select dropdown option by going through
arrowkey(not mouse) and populating selected option using spacebar(keycode- 32).
Add properties to hold the selected fruit and the currently displayed fruits (filtered ones):
selectedFruit = -1;
displayedFruits = ;
After view init, subscribe to changes on keyManager to get the selected option and to changes on filtered fruits to get the filtered list and store it on displayedFruits :
ngAfterViewInit() {
this.matAutocomplete._keyManager.change.subscribe((index) => {
if (index >= 0) {
this.selectedFruit = index;
}
})
this.filteredFruits.subscribe((filteredFruits) => {
this.displayedFruits = filteredFruits;
});
}
On add method, include an else clause to include the fruit and reset selectedFruit to -1:
add(event: MatChipInputEvent): void {
// Add fruit only when MatAutocomplete is not open
// To make sure this does not conflict with OptionSelected Event
if (!this.matAutocomplete.isOpen) {
// ...
} else {
if (this.selectedFruit >= 0) {
this.fruits.push(this.displayedFruits[this.selectedFruit])
this.fruitInput.nativeElement.value = '';
this.fruitCtrl.setValue(null);
} else if (this.fruitInput.nativeElement.value !== '' && this.displayedFruits.length === 0) {
this.fruits.push(this.fruitInput.nativeElement.value)
this.fruitInput.nativeElement.value = '';
this.fruitCtrl.setValue(null);
}
}
this.selectedFruit = -1;
}
2)How to remove option from dropdown that is already populated or used.
Enhance the filter to also check for already used fruit:
private _filter(value: string): string {
const filterValue = value.toLowerCase();
return this.allFruits.filter(fruit => fruit.toLowerCase().indexOf(filterValue) === 0 && !this.fruits.find( existingFruit => existingFruit === fruit ));
}
3)Show dropdown only when user enters some charcter in input text else show
class="info"` text only in dropdown, when no input text is there and no
option in dropdown matches enter charcters in input.
If I got it right, you may do this:
Bind to input focus event to show autocomplete when input is focused
<input
placeholder="New fruit..."
#fruitInput
(focus)="matAutocomplete.showPanel = true"
[formControl]="fruitCtrl"
[matAutocomplete]="auto"
[matChipInputFor]="chipList"
[matChipInputSeparatorKeyCodes]="separatorKeysCodes"
[matChipInputAddOnBlur]="addOnBlur"
(matChipInputTokenEnd)="add($event)">
Modify your autocomplete template to show an extra class="info" option when no text is entered or no value matches:
<mat-autocomplete #auto="matAutocomplete" (optionSelected)="selected($event)">
<mat-option class="info" *ngIf="displayedFruits.length === 0 || fruitInput.value === ''" disabled>Test</mat-option>
<ng-container *ngIf="fruitInput.value !== ''">
<mat-option *ngFor="let fruit of displayedFruits" [value]="fruit">
{{fruit}}
</mat-option>
</ng-container>
</mat-autocomplete>
Working stackblitz here
Thanks, Please suggest some solution for 2 and 3 part.
– Mahi
Nov 29 '18 at 3:49
@Ahmadmnzr I've updated the answer and stackblitz with points 2 and 3.
– GCSDC
Nov 29 '18 at 5:37
There is a bug in your implementation, user is unable to create chips by just writing in input and then pressing ENTER or space Key.(Please have a look at my stackblitz), if user does not want dropdown options.
– Mahi
Nov 29 '18 at 8:19
Did a little change on the add method.
– GCSDC
Nov 29 '18 at 14:46
Its not working. Its adding chip even when input is empty onpressing of space key and enter key.
– Mahi
Nov 29 '18 at 14:56
|
show 3 more comments
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53525798%2fangular-material-mat-chip-autocompleteinput-on-selecting-dropdown-through-s%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
1) How to add select dropdown option by going through
arrowkey(not mouse) and populating selected option using spacebar(keycode- 32).
Add properties to hold the selected fruit and the currently displayed fruits (filtered ones):
selectedFruit = -1;
displayedFruits = ;
After view init, subscribe to changes on keyManager to get the selected option and to changes on filtered fruits to get the filtered list and store it on displayedFruits :
ngAfterViewInit() {
this.matAutocomplete._keyManager.change.subscribe((index) => {
if (index >= 0) {
this.selectedFruit = index;
}
})
this.filteredFruits.subscribe((filteredFruits) => {
this.displayedFruits = filteredFruits;
});
}
On add method, include an else clause to include the fruit and reset selectedFruit to -1:
add(event: MatChipInputEvent): void {
// Add fruit only when MatAutocomplete is not open
// To make sure this does not conflict with OptionSelected Event
if (!this.matAutocomplete.isOpen) {
// ...
} else {
if (this.selectedFruit >= 0) {
this.fruits.push(this.displayedFruits[this.selectedFruit])
this.fruitInput.nativeElement.value = '';
this.fruitCtrl.setValue(null);
} else if (this.fruitInput.nativeElement.value !== '' && this.displayedFruits.length === 0) {
this.fruits.push(this.fruitInput.nativeElement.value)
this.fruitInput.nativeElement.value = '';
this.fruitCtrl.setValue(null);
}
}
this.selectedFruit = -1;
}
2)How to remove option from dropdown that is already populated or used.
Enhance the filter to also check for already used fruit:
private _filter(value: string): string {
const filterValue = value.toLowerCase();
return this.allFruits.filter(fruit => fruit.toLowerCase().indexOf(filterValue) === 0 && !this.fruits.find( existingFruit => existingFruit === fruit ));
}
3)Show dropdown only when user enters some charcter in input text else show
class="info"` text only in dropdown, when no input text is there and no
option in dropdown matches enter charcters in input.
If I got it right, you may do this:
Bind to input focus event to show autocomplete when input is focused
<input
placeholder="New fruit..."
#fruitInput
(focus)="matAutocomplete.showPanel = true"
[formControl]="fruitCtrl"
[matAutocomplete]="auto"
[matChipInputFor]="chipList"
[matChipInputSeparatorKeyCodes]="separatorKeysCodes"
[matChipInputAddOnBlur]="addOnBlur"
(matChipInputTokenEnd)="add($event)">
Modify your autocomplete template to show an extra class="info" option when no text is entered or no value matches:
<mat-autocomplete #auto="matAutocomplete" (optionSelected)="selected($event)">
<mat-option class="info" *ngIf="displayedFruits.length === 0 || fruitInput.value === ''" disabled>Test</mat-option>
<ng-container *ngIf="fruitInput.value !== ''">
<mat-option *ngFor="let fruit of displayedFruits" [value]="fruit">
{{fruit}}
</mat-option>
</ng-container>
</mat-autocomplete>
Working stackblitz here
Thanks, Please suggest some solution for 2 and 3 part.
– Mahi
Nov 29 '18 at 3:49
@Ahmadmnzr I've updated the answer and stackblitz with points 2 and 3.
– GCSDC
Nov 29 '18 at 5:37
There is a bug in your implementation, user is unable to create chips by just writing in input and then pressing ENTER or space Key.(Please have a look at my stackblitz), if user does not want dropdown options.
– Mahi
Nov 29 '18 at 8:19
Did a little change on the add method.
– GCSDC
Nov 29 '18 at 14:46
Its not working. Its adding chip even when input is empty onpressing of space key and enter key.
– Mahi
Nov 29 '18 at 14:56
|
show 3 more comments
1) How to add select dropdown option by going through
arrowkey(not mouse) and populating selected option using spacebar(keycode- 32).
Add properties to hold the selected fruit and the currently displayed fruits (filtered ones):
selectedFruit = -1;
displayedFruits = ;
After view init, subscribe to changes on keyManager to get the selected option and to changes on filtered fruits to get the filtered list and store it on displayedFruits :
ngAfterViewInit() {
this.matAutocomplete._keyManager.change.subscribe((index) => {
if (index >= 0) {
this.selectedFruit = index;
}
})
this.filteredFruits.subscribe((filteredFruits) => {
this.displayedFruits = filteredFruits;
});
}
On add method, include an else clause to include the fruit and reset selectedFruit to -1:
add(event: MatChipInputEvent): void {
// Add fruit only when MatAutocomplete is not open
// To make sure this does not conflict with OptionSelected Event
if (!this.matAutocomplete.isOpen) {
// ...
} else {
if (this.selectedFruit >= 0) {
this.fruits.push(this.displayedFruits[this.selectedFruit])
this.fruitInput.nativeElement.value = '';
this.fruitCtrl.setValue(null);
} else if (this.fruitInput.nativeElement.value !== '' && this.displayedFruits.length === 0) {
this.fruits.push(this.fruitInput.nativeElement.value)
this.fruitInput.nativeElement.value = '';
this.fruitCtrl.setValue(null);
}
}
this.selectedFruit = -1;
}
2)How to remove option from dropdown that is already populated or used.
Enhance the filter to also check for already used fruit:
private _filter(value: string): string {
const filterValue = value.toLowerCase();
return this.allFruits.filter(fruit => fruit.toLowerCase().indexOf(filterValue) === 0 && !this.fruits.find( existingFruit => existingFruit === fruit ));
}
3)Show dropdown only when user enters some charcter in input text else show
class="info"` text only in dropdown, when no input text is there and no
option in dropdown matches enter charcters in input.
If I got it right, you may do this:
Bind to input focus event to show autocomplete when input is focused
<input
placeholder="New fruit..."
#fruitInput
(focus)="matAutocomplete.showPanel = true"
[formControl]="fruitCtrl"
[matAutocomplete]="auto"
[matChipInputFor]="chipList"
[matChipInputSeparatorKeyCodes]="separatorKeysCodes"
[matChipInputAddOnBlur]="addOnBlur"
(matChipInputTokenEnd)="add($event)">
Modify your autocomplete template to show an extra class="info" option when no text is entered or no value matches:
<mat-autocomplete #auto="matAutocomplete" (optionSelected)="selected($event)">
<mat-option class="info" *ngIf="displayedFruits.length === 0 || fruitInput.value === ''" disabled>Test</mat-option>
<ng-container *ngIf="fruitInput.value !== ''">
<mat-option *ngFor="let fruit of displayedFruits" [value]="fruit">
{{fruit}}
</mat-option>
</ng-container>
</mat-autocomplete>
Working stackblitz here
Thanks, Please suggest some solution for 2 and 3 part.
– Mahi
Nov 29 '18 at 3:49
@Ahmadmnzr I've updated the answer and stackblitz with points 2 and 3.
– GCSDC
Nov 29 '18 at 5:37
There is a bug in your implementation, user is unable to create chips by just writing in input and then pressing ENTER or space Key.(Please have a look at my stackblitz), if user does not want dropdown options.
– Mahi
Nov 29 '18 at 8:19
Did a little change on the add method.
– GCSDC
Nov 29 '18 at 14:46
Its not working. Its adding chip even when input is empty onpressing of space key and enter key.
– Mahi
Nov 29 '18 at 14:56
|
show 3 more comments
1) How to add select dropdown option by going through
arrowkey(not mouse) and populating selected option using spacebar(keycode- 32).
Add properties to hold the selected fruit and the currently displayed fruits (filtered ones):
selectedFruit = -1;
displayedFruits = ;
After view init, subscribe to changes on keyManager to get the selected option and to changes on filtered fruits to get the filtered list and store it on displayedFruits :
ngAfterViewInit() {
this.matAutocomplete._keyManager.change.subscribe((index) => {
if (index >= 0) {
this.selectedFruit = index;
}
})
this.filteredFruits.subscribe((filteredFruits) => {
this.displayedFruits = filteredFruits;
});
}
On add method, include an else clause to include the fruit and reset selectedFruit to -1:
add(event: MatChipInputEvent): void {
// Add fruit only when MatAutocomplete is not open
// To make sure this does not conflict with OptionSelected Event
if (!this.matAutocomplete.isOpen) {
// ...
} else {
if (this.selectedFruit >= 0) {
this.fruits.push(this.displayedFruits[this.selectedFruit])
this.fruitInput.nativeElement.value = '';
this.fruitCtrl.setValue(null);
} else if (this.fruitInput.nativeElement.value !== '' && this.displayedFruits.length === 0) {
this.fruits.push(this.fruitInput.nativeElement.value)
this.fruitInput.nativeElement.value = '';
this.fruitCtrl.setValue(null);
}
}
this.selectedFruit = -1;
}
2)How to remove option from dropdown that is already populated or used.
Enhance the filter to also check for already used fruit:
private _filter(value: string): string {
const filterValue = value.toLowerCase();
return this.allFruits.filter(fruit => fruit.toLowerCase().indexOf(filterValue) === 0 && !this.fruits.find( existingFruit => existingFruit === fruit ));
}
3)Show dropdown only when user enters some charcter in input text else show
class="info"` text only in dropdown, when no input text is there and no
option in dropdown matches enter charcters in input.
If I got it right, you may do this:
Bind to input focus event to show autocomplete when input is focused
<input
placeholder="New fruit..."
#fruitInput
(focus)="matAutocomplete.showPanel = true"
[formControl]="fruitCtrl"
[matAutocomplete]="auto"
[matChipInputFor]="chipList"
[matChipInputSeparatorKeyCodes]="separatorKeysCodes"
[matChipInputAddOnBlur]="addOnBlur"
(matChipInputTokenEnd)="add($event)">
Modify your autocomplete template to show an extra class="info" option when no text is entered or no value matches:
<mat-autocomplete #auto="matAutocomplete" (optionSelected)="selected($event)">
<mat-option class="info" *ngIf="displayedFruits.length === 0 || fruitInput.value === ''" disabled>Test</mat-option>
<ng-container *ngIf="fruitInput.value !== ''">
<mat-option *ngFor="let fruit of displayedFruits" [value]="fruit">
{{fruit}}
</mat-option>
</ng-container>
</mat-autocomplete>
Working stackblitz here
1) How to add select dropdown option by going through
arrowkey(not mouse) and populating selected option using spacebar(keycode- 32).
Add properties to hold the selected fruit and the currently displayed fruits (filtered ones):
selectedFruit = -1;
displayedFruits = ;
After view init, subscribe to changes on keyManager to get the selected option and to changes on filtered fruits to get the filtered list and store it on displayedFruits :
ngAfterViewInit() {
this.matAutocomplete._keyManager.change.subscribe((index) => {
if (index >= 0) {
this.selectedFruit = index;
}
})
this.filteredFruits.subscribe((filteredFruits) => {
this.displayedFruits = filteredFruits;
});
}
On add method, include an else clause to include the fruit and reset selectedFruit to -1:
add(event: MatChipInputEvent): void {
// Add fruit only when MatAutocomplete is not open
// To make sure this does not conflict with OptionSelected Event
if (!this.matAutocomplete.isOpen) {
// ...
} else {
if (this.selectedFruit >= 0) {
this.fruits.push(this.displayedFruits[this.selectedFruit])
this.fruitInput.nativeElement.value = '';
this.fruitCtrl.setValue(null);
} else if (this.fruitInput.nativeElement.value !== '' && this.displayedFruits.length === 0) {
this.fruits.push(this.fruitInput.nativeElement.value)
this.fruitInput.nativeElement.value = '';
this.fruitCtrl.setValue(null);
}
}
this.selectedFruit = -1;
}
2)How to remove option from dropdown that is already populated or used.
Enhance the filter to also check for already used fruit:
private _filter(value: string): string {
const filterValue = value.toLowerCase();
return this.allFruits.filter(fruit => fruit.toLowerCase().indexOf(filterValue) === 0 && !this.fruits.find( existingFruit => existingFruit === fruit ));
}
3)Show dropdown only when user enters some charcter in input text else show
class="info"` text only in dropdown, when no input text is there and no
option in dropdown matches enter charcters in input.
If I got it right, you may do this:
Bind to input focus event to show autocomplete when input is focused
<input
placeholder="New fruit..."
#fruitInput
(focus)="matAutocomplete.showPanel = true"
[formControl]="fruitCtrl"
[matAutocomplete]="auto"
[matChipInputFor]="chipList"
[matChipInputSeparatorKeyCodes]="separatorKeysCodes"
[matChipInputAddOnBlur]="addOnBlur"
(matChipInputTokenEnd)="add($event)">
Modify your autocomplete template to show an extra class="info" option when no text is entered or no value matches:
<mat-autocomplete #auto="matAutocomplete" (optionSelected)="selected($event)">
<mat-option class="info" *ngIf="displayedFruits.length === 0 || fruitInput.value === ''" disabled>Test</mat-option>
<ng-container *ngIf="fruitInput.value !== ''">
<mat-option *ngFor="let fruit of displayedFruits" [value]="fruit">
{{fruit}}
</mat-option>
</ng-container>
</mat-autocomplete>
Working stackblitz here
edited Nov 29 '18 at 21:20
answered Nov 29 '18 at 1:17
GCSDCGCSDC
791620
791620
Thanks, Please suggest some solution for 2 and 3 part.
– Mahi
Nov 29 '18 at 3:49
@Ahmadmnzr I've updated the answer and stackblitz with points 2 and 3.
– GCSDC
Nov 29 '18 at 5:37
There is a bug in your implementation, user is unable to create chips by just writing in input and then pressing ENTER or space Key.(Please have a look at my stackblitz), if user does not want dropdown options.
– Mahi
Nov 29 '18 at 8:19
Did a little change on the add method.
– GCSDC
Nov 29 '18 at 14:46
Its not working. Its adding chip even when input is empty onpressing of space key and enter key.
– Mahi
Nov 29 '18 at 14:56
|
show 3 more comments
Thanks, Please suggest some solution for 2 and 3 part.
– Mahi
Nov 29 '18 at 3:49
@Ahmadmnzr I've updated the answer and stackblitz with points 2 and 3.
– GCSDC
Nov 29 '18 at 5:37
There is a bug in your implementation, user is unable to create chips by just writing in input and then pressing ENTER or space Key.(Please have a look at my stackblitz), if user does not want dropdown options.
– Mahi
Nov 29 '18 at 8:19
Did a little change on the add method.
– GCSDC
Nov 29 '18 at 14:46
Its not working. Its adding chip even when input is empty onpressing of space key and enter key.
– Mahi
Nov 29 '18 at 14:56
Thanks, Please suggest some solution for 2 and 3 part.
– Mahi
Nov 29 '18 at 3:49
Thanks, Please suggest some solution for 2 and 3 part.
– Mahi
Nov 29 '18 at 3:49
@Ahmadmnzr I've updated the answer and stackblitz with points 2 and 3.
– GCSDC
Nov 29 '18 at 5:37
@Ahmadmnzr I've updated the answer and stackblitz with points 2 and 3.
– GCSDC
Nov 29 '18 at 5:37
There is a bug in your implementation, user is unable to create chips by just writing in input and then pressing ENTER or space Key.(Please have a look at my stackblitz), if user does not want dropdown options.
– Mahi
Nov 29 '18 at 8:19
There is a bug in your implementation, user is unable to create chips by just writing in input and then pressing ENTER or space Key.(Please have a look at my stackblitz), if user does not want dropdown options.
– Mahi
Nov 29 '18 at 8:19
Did a little change on the add method.
– GCSDC
Nov 29 '18 at 14:46
Did a little change on the add method.
– GCSDC
Nov 29 '18 at 14:46
Its not working. Its adding chip even when input is empty onpressing of space key and enter key.
– Mahi
Nov 29 '18 at 14:56
Its not working. Its adding chip even when input is empty onpressing of space key and enter key.
– Mahi
Nov 29 '18 at 14:56
|
show 3 more comments
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53525798%2fangular-material-mat-chip-autocompleteinput-on-selecting-dropdown-through-s%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
It seems that if the list component is focused, space key works the same as enter. On the stackblitz you provided, I tried inspecting one of the elements of the list, then returned to the list, pressed space key and it was selected. Maybe knowing this may help you implement what you're looking for.
– GCSDC
Nov 28 '18 at 20:09
Its not working. You don't have to use mouse to open dropdown. When input is focus just use arrow key to select a particular option and click space key to select that option. However, enter key is working.
– Mahi
Nov 28 '18 at 20:14
Have you reviewed this? space doesn't seem to be an option for autocomplete material.angular.io/components/autocomplete/…
– Marshal
Nov 28 '18 at 20:41
Thanks, Keyboard interaction DOWN_ARROW: Next option becomes active.UP_ARROW: Previous option becomes active.ENTER: Select currently active item.
– Mahi
Nov 28 '18 at 20:46
But, it can also be selected using space key. That is requirement
– Mahi
Nov 28 '18 at 20:47