簡體   English   中英

Angular - 在輸入字段上寫@ 后顯示下拉列表

[英]Angular - Show dropdown after write @ on input field

我的目標是當我開始在輸入字段上寫@顯示一個下拉菜單

我的組件

  myControl: FormControl = new FormControl();

  options = [
    'One',
    'Two',
    'Three'
  ];

  filteredOptions: Observable<string[]>;

  ngOnInit() {
    this.filteredOptions = this.myControl.valueChanges
      .pipe(
        startWith('@'),
        map(val => val.length >= 1 ? this.filter(val): [])
      );
  }

  filter(val: string): string[] {
    return this.options.filter(option =>
      option.toLowerCase().indexOf(val.toLowerCase()) === 0);
    console.log(this.options)
  }

這是我所做的,但它不起作用。

HTML

<form class="example-form">
  <mat-form-field class="example-full-width">
    <input #inputField type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="auto">
    <mat-autocomplete #auto="matAutocomplete">
      <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
        {{ option }}
      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
</form>

您的訂閱效果很好。

您只是忘記轉義@ in filter函數,因為您的選項 List 中沒有@

嘗試這個 :

filter(val: string): string[] {
  return this.options.filter(option =>
    option.toLowerCase().indexOf(val.toLowerCase().replace('@', '')) === 0);
}

只需在您的輸入上注冊更改事件 - 例如:

(change)='handlerMethode($event)'

檢查@索引的輸入,如果你發現做你想做的。

暫無
暫無

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

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