簡體   English   中英

Angular Material Autocomplete - 如何允許用戶添加不在建議列表中的項目?

[英]Angular Material Autocomplete - How to allow user to add item not in suggested list?

我正在嘗試從Angular Material實現自動完成組件:

https://material.angular.io/components/autocomplete/overview

它適用於讓用戶從建議列表中選擇特定項目但我還想允許用戶添加不在列表中的項目。

所以我們說建議列表包含以下內容:

Cats
Birds
Dogs

並且用戶開始鍵入"Do"並且自動完成顯示"Dogs"作為建議選項(因為我也根據他們鍵入的內容過濾列表)。 但隨后用戶繼續輸入"Dolls" ,現在自動完成建議中沒有顯示任何內容。 然后用戶點擊進入並將其添加到列表中。

當前行為是,如果列表中不存在用戶鍵入的內容,則他們無法添加該項目。

如果將enter鍵偵聽器添加到輸入字段,則可以處理輸入的值並將其添加到選項(如果它不存在)。 您還可以將用戶輸入的任何內容動態添加到已過濾選項列表中作為“添加新項目”選項,或向該字段添加“添加”圖標(例如,作為matSuffix)。 或者你可以做到這三點:

Stackblitz

HTML

<form class="example-form">
  <mat-form-field class="example-full-width">
    <input matInput placeholder="Item" aria-label="Item" [matAutocomplete]="auto" [formControl]="itemCtrl" (keyup.enter)="addOption()">
    <mat-autocomplete #auto="matAutocomplete" (optionSelected)="optionSelected($event.option)">
      <mat-option *ngFor="let item of filteredItems | async" [value]="item">
        <span>{{ item }}</span>
      </mat-option>
    </mat-autocomplete>
    <button *ngIf="showAddButton && itemCtrl.value" matSuffix mat-button mat-icon-button (click)="addOption()"><mat-icon matTooltip='Add "{{itemCtrl.value}}"'>add</mat-icon></button>
  </mat-form-field>
</form>

TS

import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';

import { Observable } from 'rxjs/Observable';
import { startWith } from 'rxjs/operators/startWith';
import { map } from 'rxjs/operators/map';

/**
 * @title Autocomplete with add new item option
 */
@Component({
  selector: 'autocomplete-overview-example',
  templateUrl: 'autocomplete-overview-example.html',
  styleUrls: ['autocomplete-overview-example.css']
})
export class AutocompleteOverviewExample {
  itemCtrl: FormControl;
  filteredItems: Observable<any[]>;
  showAddButton: boolean = false;

  prompt = 'Press <enter> to add "';

  items: string[] = [
    'Cats',
    'Birds',
    'Dogs'
  ];

  constructor() {
    this.itemCtrl = new FormControl();
    this.filteredItems = this.itemCtrl.valueChanges
      .pipe(
      startWith(''),
      map(item => item ? this.filterItems(item) : this.items.slice())
      );
  }

  filterItems(name: string) {
    let results = this.items.filter(item =>
      item.toLowerCase().indexOf(name.toLowerCase()) === 0);

    this.showAddButton = results.length === 0;
    if (this.showAddButton) {
      results = [this.prompt + name + '"'];
    }

    return results;
  }

  optionSelected(option) {
    if (option.value.indexOf(this.prompt) === 0) {
      this.addOption();
    }
  }

  addOption() {
    let option = this.removePromptFromOption(this.itemCtrl.value);
    if (!this.items.some(entry => entry === option)) {
      const index = this.items.push(option) - 1;
      this.itemCtrl.setValue(this.items[index]);
    }
  }

  removePromptFromOption(option) {
    if (option.startsWith(this.prompt)) {
      option = option.substring(this.prompt.length, option.length -1);
    }
    return option;
  }
}

用戶可以在建議列表中添加項目,這很奇怪。 該列表由知道建議內容的人向用戶建議。 但無論如何...

用戶可以在字段中鍵入任何內容並忽略建議。 通過忽略建議的並輸入玩偶 ,用戶可以按下“添加”按鈕,這將把輸入的任何內容( 玩偶 )添加到options數組中。

例如,您可以通過監聽表單上的提交事件來執行此操作:

(ngSubmit)="options.push(myControl.value); myControl.reset()"

這是完整的演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM