Angular - Show dropdown after write @ on input field

自闭症网瘾萝莉.ら 提交于 2020-03-03 07:31:33

问题


My Objective is to show a dropdown menu when i start to write @ on the input field.

My Component

  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)
  }

This is what i have done, but its not working.

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>

回答1:


Your subscription is working great.

You just forget to escape the @ in filter function since you don't have an @ in your option List.

Try this :

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



回答2:


Just register to the change event on your input - for example:

(change)='handlerMethode($event)'

Check input for index of @ and if you find do what you want.



来源:https://stackoverflow.com/questions/60476559/angular-show-dropdown-after-write-on-input-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!