【问题标题】:Clear Angular Material autocomplete after selection选择后清除 Angular Material 自动完成
【发布时间】:2018-02-26 08:08:49
【问题描述】:

我遇到的问题如下:我需要的行为是,当从自动完成输入中选择一个选项时,它应该向 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 文档,但没有找到执行此操作的方法。

谢谢。

【问题讨论】:

    标签: angular typescript autocomplete angular-material2


    【解决方案1】:

    我想你已经接近了,看起来唯一缺少的部分是重置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;
    }
    

    【讨论】:

    • 如果没有选择值,清除输入怎么办?在这种情况下,我尝试使用输入的 blur() 事件,但在这种情况下,我无法访问自动完成值(如果选择或未选择)。有什么想法吗?
    【解决方案2】:

    这是我的方法

    在模板中

    ...
    <md-autocomplete #auto="mdAutocomplete" [displayWith]="displayNull" (optionSelected)="selectHandler($event)">
    ...
    

    在component.ts中

    public selectHandler(event : MdAutocompleteSelectedEvent) : void
    {
        event.option.deselect()
        this.doStuffWith(event.option.value)
    }
    
    public displayNull()
    {
        return null
    }
    

    【讨论】:

    • 我没有使用 ReactiveForm,所以这对我来说很棒
    【解决方案3】:

    遇到了这个解决方案,但我不喜欢 displayNull 修复。

    我的解决方案与此类似:

    component.html:

      <input matInput [matAutocomplete]="auto" (input)="filter($event.target.value)" #autoInput>
      <mat-autocomplete #auto [displayWith]="displayKey" (optionSelected)="emit($event, autoInput)">
      // ...
      </mat-autocomplete>
    

    component.ts:

    @Output() optionSelected = new EventEmitter<MatAutocompleteSelectedEvent>();
    
    emit(event: MatAutocompleteSelectedEvent, ele: HTMLInputElement) {
      ele.value = '';
      ele.blur();
      this.filter('');
      this.optionSelected.emit(event);
    }
    

    【讨论】:

    • 这似乎是唯一适用于角度材料 >=12 的解决方案。当没有附加到自动完成时,formControl 上的 setValue 可以正常工作。
    【解决方案4】:

    如果您使用反应式表单,最简单的方法是获取控件将值设置为空字符串

    就我而言,我必须这样做:

    <input [matAutocomplete]="auto" formControlName="currentContact" type="text" matInput placeholder="Locatie">
    
    this.reactiveForm = this.formBuilder.group({currentContact: ['']})
    this.reactiveForm.get('currentContact').setValue('');
    

    【讨论】:

      猜你喜欢
      • 2015-12-29
      • 2018-11-27
      • 2020-05-04
      • 2022-10-21
      • 2014-01-14
      • 2018-01-20
      • 2011-02-03
      • 2019-02-25
      • 2012-07-21
      相关资源
      最近更新 更多