【问题标题】:Angular Material=> Mat-chip- Autocomplete(input) on selecting dropdown through space keyAngular Material=> Mat-chip- Autocomplete(input) 通过空格键选择下拉菜单
【发布时间】:2019-04-30 17:39:38
【问题描述】:

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

但是,当我们通过箭头键选择下拉菜单然后按回车键(keycode-13)但在空格键(keycode-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);
  }
}

【问题讨论】:

  • 似乎如果列表组件被聚焦,空格键的作用与回车相同。在您提供的 stackblitz 上,我尝试检查列表中的一个元素,然后返回列表,按空格键并被选中。也许知道这一点可以帮助您实现您正在寻找的东西。
  • 它不工作。您不必使用鼠标打开下拉菜单。当输入为焦点时,只需使用箭头键选择特定选项,然后单击空格键选择该选项。但是,输入键正在工作。
  • 您查看过这个吗?空间似乎不是自动完成的选项material.angular.io/components/autocomplete/…
  • 谢谢,键盘交互 DOWN_ARROW:下一个选项变为活动状态。UP_ARROW:上一个选项变为活动状态。ENTER:选择当前活动项目。
  • 但是,也可以使用空格键选择。这是要求

标签: angular typescript angular-material angular7


【解决方案1】:

1) 如何通过浏览添加选择下拉选项 箭头键(不是鼠标)并使用空格键(keycode- 32)填充选定的选项。

  1. 添加属性以保存选定的水果和当前显示的水果(过滤的):

    selectedFruit = -1; displayedFruits = [];

  2. 查看初始化后,订阅 keyManager 上的更改以获取所选选项,并订阅过滤水果的更改以获取过滤列表并将其存储在 displayFruits 上:

ngAfterViewInit() {
  this.matAutocomplete._keyManager.change.subscribe((index) => {
    if (index >= 0) {
      this.selectedFruit = index;
    }
  })
  this.filteredFruits.subscribe((filteredFruits) => {
    this.displayedFruits = filteredFruits;
  });
}
  1. 在 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"` 文本仅在下拉列表中,当没有输入文本并且没有 下拉菜单中的选项匹配输入中的输入字符。

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

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

工作堆栈闪电战here

【讨论】:

  • 谢谢,请为第 2 部分和第 3 部分提出一些解决方案。
  • @Ahmadmnzr 我已经用第 2 点和第 3 点更新了答案和 stackblitz。
  • 您的实现中存在一个错误,用户无法通过仅写入输入然后按 ENTER 或空格键来创建芯片。(请查看我的 stackblitz),如果用户不想要下拉选项。
  • 对add方法做了一点改动。
  • 它不工作。按下空格键和回车键,即使输入为空也可以加筹码。
猜你喜欢
  • 2016-10-01
  • 2018-10-02
  • 2018-04-23
  • 1970-01-01
  • 1970-01-01
  • 2020-08-03
  • 1970-01-01
  • 2022-11-10
  • 2015-05-15
相关资源
最近更新 更多