【问题标题】:Angular - Show dropdown after write @ on input fieldAngular - 在输入字段上写@后显示下拉列表
【发布时间】:2020-03-01 15:16:01
【问题描述】:

我的目标是当我开始在输入字段上写 @显示一个下拉菜单

我的组件

  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>

【问题讨论】:

  • 好吧,您并没有真正将模板中的输入与代码中的输入连接起来...在角度文档中查找 ViewChild Decorator...然后您通过其#marker 选择输入并且应该能够访问它...或者您使用 (change) 事件来注册一个处理程序 Methode,如下所述...我将在我在家时添加一个示例
  • 谢谢@Florian,我很感激

标签: javascript angular typescript forms rxjs


【解决方案1】:

您的订阅效果很好。

您只是忘记在 filter 函数中转义 @,因为您的 选项列表 中没有 @

试试这个:

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

【讨论】:

    【解决方案2】:

    只需在您的输入中注册更改事件 - 例如:

    (change)='handlerMethode($event)'
    

    检查输入以查找@ 的索引,如果找到,请执行您想要的操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-26
      • 1970-01-01
      • 1970-01-01
      • 2011-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多