How to use mat-autocomplete (Angular Material Auto

2020-02-01 08:41发布

let's say I have the following form structure:

  this.myForm = this.formBuilder.group({
          date: ['', [Validators.required]],
          notes: [''],
          items: this.initItems()

        });
  initItems() {
    var formArray = this.formBuilder.array([]);
    for (let i = 0; i < 2; i++) {
      formArray.push(this.formBuilder.group({
        name: ['', [Validators.required]],
        age: ['', [Validators.required]],
      }));
    }

    return formArray;
  }

and the name control supposed to be an autocomplete, how can I relate the all the name controls to an autocomplete list?

1条回答
男人必须洒脱
2楼-- · 2020-02-01 09:07

I solved this by relating each name control inside the FormArray to a filteredOption array:

  ManageNameControl(index: number) {
    var arrayControl = this.myForm.get('items') as FormArray;
    this.filteredOptions[index] = arrayControl.at(index).get('name').valueChanges
      .pipe(
      startWith<string | User>(''),
      map(value => typeof value === 'string' ? value : value.name),
      map(name => name ? this._filter(name) : this.options.slice())
      );

  }

Then After each time I build a formgroup inside the form Array (create new item), I need to call the above function at the new index like this:

  addNewItem() {
    const controls = <FormArray>this.myForm.controls['items'];
    let formGroup = this.formBuilder.group({
      name: ['', [Validators.required]],
      age: ['', [Validators.required]],
    });
    controls.push(formGroup);
    // Build the account Auto Complete values
    this.ManageNameControl(controls.length - 1);

  }

In the .html file, we need to refer to the desired filteredOption array, we can do this by using the i index:

  <mat-option *ngFor="let option of filteredOptions[i] | async " [value]="option">
  {{ option.name }}
  </mat-option>

please see the detailed answer here https://stackblitz.com/edit/angular-szxkme?file=app%2Fautocomplete-display-example.ts

查看更多
登录 后发表回答