Angular Material=> Mat-chip- 通过 space 键选择下拉菜单时自动完成(输入)
Angular Material=> Mat-chip- Autocomplete(input) on selecting dropdown through space key
当我们 select mat-option
时如何填充 mat-chip
onkeypress(spacebar)
通过箭头键进入选项并按 space 键 (32)。
但是,当我们 select 下拉菜单通过箭头键转到选项然后按回车键(键码 - 13)但在 space 键(键码 - 32).
这里是 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);
}
}
1) How to add select dropdown option by going through
arrowkey(not mouse) and populating selected option using spacebar(keycode- 32).
添加属性来保存选中的水果和当前显示的水果(过滤后的):
selectedFruit = -1;
displayedFruits = [];
view init后,订阅keyManager上的changes获取选中的option,订阅filtered fruits上的changes获取过滤后的列表存储在displayedFruits上:
ngAfterViewInit() {
this.matAutocomplete._keyManager.change.subscribe((index) => {
if (index >= 0) {
this.selectedFruit = index;
}
})
this.filteredFruits.subscribe((filteredFruits) => {
this.displayedFruits = filteredFruits;
});
}
- 在 add 方法中,包含一个 else 子句以包含水果并将 selectedFruit 重置为 -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.
增强过滤器以检查已经使用过的水果:
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.
如果我没猜错,你可以这样做:
- 绑定到输入焦点事件以在输入焦点时显示自动完成
<input
placeholder="New fruit..."
#fruitInput
(focus)="matAutocomplete.showPanel = true"
[formControl]="fruitCtrl"
[matAutocomplete]="auto"
[matChipInputFor]="chipList"
[matChipInputSeparatorKeyCodes]="separatorKeysCodes"
[matChipInputAddOnBlur]="addOnBlur"
(matChipInputTokenEnd)="add($event)">
- 修改您的自动完成模板以在未输入文本或未匹配任何值时显示额外的 class="info" 选项:
<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>
工作 stackblitz here
当我们 select mat-option
时如何填充 mat-chip
onkeypress(spacebar)
通过箭头键进入选项并按 space 键 (32)。
但是,当我们 select 下拉菜单通过箭头键转到选项然后按回车键(键码 - 13)但在 space 键(键码 - 32).
这里是 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);
}
}
1) How to add select dropdown option by going through arrowkey(not mouse) and populating selected option using spacebar(keycode- 32).
添加属性来保存选中的水果和当前显示的水果(过滤后的):
selectedFruit = -1; displayedFruits = [];
view init后,订阅keyManager上的changes获取选中的option,订阅filtered fruits上的changes获取过滤后的列表存储在displayedFruits上:
ngAfterViewInit() {
this.matAutocomplete._keyManager.change.subscribe((index) => {
if (index >= 0) {
this.selectedFruit = index;
}
})
this.filteredFruits.subscribe((filteredFruits) => {
this.displayedFruits = filteredFruits;
});
}
- 在 add 方法中,包含一个 else 子句以包含水果并将 selectedFruit 重置为 -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.
增强过滤器以检查已经使用过的水果:
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.
如果我没猜错,你可以这样做:
- 绑定到输入焦点事件以在输入焦点时显示自动完成
<input
placeholder="New fruit..."
#fruitInput
(focus)="matAutocomplete.showPanel = true"
[formControl]="fruitCtrl"
[matAutocomplete]="auto"
[matChipInputFor]="chipList"
[matChipInputSeparatorKeyCodes]="separatorKeysCodes"
[matChipInputAddOnBlur]="addOnBlur"
(matChipInputTokenEnd)="add($event)">
- 修改您的自动完成模板以在未输入文本或未匹配任何值时显示额外的 class="info" 选项:
<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>
工作 stackblitz here