angular - 选择后清除 Angular Material 自动完成

标签 angular typescript autocomplete angular-material2

我遇到的问题如下:我需要的行为是,当从自动完成输入中选择一个选项时,它应该向 Angular Material Chips 组件添加一个芯片(它确实如此)并且它也应该清除自动完成输入,这样我就可以选择另一个选项。

这是我的 html:

<div class="col-md-6">
   <md-form-field>
      <input type="text" placeholder="Categoría" aria-label="Categoría" mdInput [mdAutocomplete]="auto" [formControl]="categoryCtrl">
      <md-autocomplete #auto="mdAutocomplete" (optionSelected)="selectCategory($event)">
         <md-option *ngFor="let category of filteredCategories | async" [value]="category.name">
            {{ category.name }}
         </md-option>
      </md-autocomplete>
   </md-form-field>
</div>

这是我的 TypeScript 代码:

constructor(private placeService: PlaceService, private categoryService: CategoryService) {
    this.categoryCtrl = new FormControl();
    this.filteredCategories = this.categoryCtrl.valueChanges
        .startWith('')
        .map(category => category ? this.filterCategories(category) : this.categories.slice());
}

filterCategories(name: string) {
    return this.categories.filter(category => category.name.toLowerCase().indexOf(name.toLowerCase()) === 0);
}

selectCategory(category: any) {
    const index = this.selectedCategories.indexOf(category.option.value);
    if (index === -1) {
        this.selectedCategories.push(category.option.value)
    }
}

我查看了 Angular Material 文档,但没有找到执行此操作的方法。

谢谢。

最佳答案

我认为您很接近,看起来唯一缺少的部分是重置 selectCategory 中的表单控件值。这是怎么回事 我们在自己的应用程序中完成了它,但实际上是同一件事:

/** Reference to the autocomplete trigger. */
@ViewChild(MdAutocompleteTrigger)
private trigger: MdAutocompleteTrigger;

/** Form control for the input. */
searchControl = new FormControl('');

ngAfterViewInit() {
  // Clear the input and emit when a selection is made
  this.trigger.autocomplete.optionSelected
    .map(event => event.option)
    .subscribe(option => {
      // This may or may not be needed, depending on your purposes
      option.deselect();

      // Emit the selection (so parent component can add chip)
      this.selection.emit(option.value);

      // Reset the value of the input
      this.searchControl.setValue('');
    });
}

每当您选择一个值时,所选文本都会短暂“闪烁”。为了避免这种情况, 您可以使用 displayWith 属性将所选值显示为空:

<md-autocomplete #auto="mdAutocomplete" [displayWith]="displayNull">
  ...
</md-autocomplete>

/** Display function for selected autocomplete values. */
displayNull(value) {
  return null;
}

关于angular - 选择后清除 Angular Material 自动完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46268259/

相关文章:

javascript - Angular 2 : SyntaxError: Unexpected token <

javascript - 谷歌地图API放置自动填充表单onload

android - 如何根据 if 条件为 AutocompleteTextview 设置两个适配器

autocomplete - Elasticsearch自动完成其余的词

html - ionic 后退按钮在 dir=rtl 时不会改变方向,直到在 ionic 5 中重新渲染

javascript - 这个例子中的 Angular *ngFor 究竟是如何工作的?

angular - DevExtreme Angular2 Form 的自定义标签

typescript - 为未导出的 typescript 参数创建类型

javascript - 在 Angular 8 中设置动态路由

angularjs - 如何在静态方法中使用注入(inject)服务