Angular Material => Mat-chip-通过空格键选择下拉列表时自动完成(输入)

问题描述 投票:2回答:1

当我们通过箭头键选择并按空格键(32)来选择mat-chip时,如何填充onkeypress(spacebar) mat-option

但是,当我们选择下拉菜单时,通过箭头键转到选项,然后按回车键(键码-13),但在空格键(键码-32)上不能同样工作,它工作正常。

这里是stackblitz链接: - 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);
  }
}
angular typescript angular-material angular7
1个回答
2
投票

1)如何通过箭头键(而不是鼠标)添加选择下拉选项并使用空格键(键代码-32)填充所选选项。

  1. 添加属性以保存选定的水果和当前显示的水果(已过滤的水果): selectedFruit = -1; displayedFruits = [];
  2. 在查看init之后,订阅keyManager上的更改以获取所选选项并更改过滤后的水果以获取过滤后的列表并将其存储在displayedFruits上: ngAfterViewInit() { this.matAutocomplete._keyManager.change.subscribe((index) => { if (index >= 0) { this.selectedFruit = index; } }) this.filteredFruits.subscribe((filteredFruits) => { this.displayedFruits = filteredFruits; }); }
  3. 在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)如何从已填充或使用的下拉列表中删除选项。

增强过滤器以检查已使用的水果:

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)仅当用户在输入文本中输入某个字符时显示下拉菜单,否则仅在下拉列表中显示class =“info”`text,当没有输入文本且下拉列表中没有选项匹配输入中的字符时。

如果我做对了,你可以这样做:

  1. 绑定到输入焦点事件以在输入被聚焦时显示自动完成 <input placeholder="New fruit..." #fruitInput (focus)="matAutocomplete.showPanel = true" [formControl]="fruitCtrl" [matAutocomplete]="auto" [matChipInputFor]="chipList" [matChipInputSeparatorKeyCodes]="separatorKeysCodes" [matChipInputAddOnBlur]="addOnBlur" (matChipInputTokenEnd)="add($event)">
  2. 修改您的自动填充模板,以便在未输入任何文本或没有值匹配时显示额外的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

© www.soinside.com 2019 - 2024. All rights reserved.