首页 > 解决方案 > 如何在 Angular 应用程序中创建多行 mat-autocomplete 元素

问题描述

我正在构建一个角度应用程序。在我有按钮的模板中,单击它会添加新的自动完成元素。但是当我选择一个选项时出现问题,我看到其他自动完成显示先前过滤的值。我过滤方法和表单控件对于所有自动完成元素都是通用的。我试图弄清楚,如何使每个自动完成元素的表单元素和过滤器方法都是唯一的。

任何帮助或建议将不胜感激,谢谢。

这是代码片段,

模板.html


<button (click)="addelement()"> Add New Elemnt </button>
  <ng-container *ngFor="let name of names; let j = index">
    <form class="example-form">
      <mat-form-field class="example-full-width">
        <mat-label>Assignee</mat-label>
        <input type="text" matInput [formControl]="myControl" [matAutocomplete]="auto">
        <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
          <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
            {{option.name}}
          </mat-option>
        </mat-autocomplete>
      </mat-form-field>
    </form>
  </ng-container>

模板.ts

import {Component, OnInit} from '@angular/core';
import {FormControl} from '@angular/forms';
import {Observable} from 'rxjs';
import {map, startWith} from 'rxjs/operators';

export interface User {
  name: string;
}

/**
 * @title Display value autocomplete
 */
@Component({
  selector: 'autocomplete-display-example',
  templateUrl: 'autocomplete-display-example.html',
  styleUrls: ['autocomplete-display-example.css'],
})
export class AutocompleteDisplayExample implements OnInit {
  myControl = new FormControl();
  options: User[] = [
    {name: 'Mary'},
    {name: 'Shelley'},
    {name: 'Igor'}
  ];

  names=[{}]

  filteredOptions: Observable<User[]>;

  ngOnInit() {
    this.filteredOptions = this.myControl.valueChanges
      .pipe(
        startWith(''),
        map(value => typeof value === 'string' ? value : value.name),
        map(name => name ? this._filter(name) : this.options.slice())
      );
  }

  displayFn(user: User): string {
    return user && user.name ? user.name : '';
  }

  private _filter(name: string): User[] {
    const filterValue = name.toLowerCase();

    return this.options.filter(option => option.name.toLowerCase().indexOf(filterValue) === 0);
  }

  addelement() {
    this.names.push({});
  }
}

在上面的代码片段中,您将“names”数组,根据推送到此数组的对象,自动完成将出现在模板中。如果您需要更多信息,请告诉我。

标签: javascriptangularautocomplete

解决方案


推荐阅读