How to use mat-autocomplete (Angular Material Autocomplete) inside FormArray (Reactive Forms)

后端 未结 1 427
攒了一身酷
攒了一身酷 2020-12-10 13:28

let\'s say I have the following form structure:

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


        
1条回答
  •  有刺的猬
    2020-12-10 14:20

    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(''),
          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 = 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:

      
      {{ option.name }}
      
    

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

    Update: to populate the array with a default value for a specific object, you can do it using the receive forms like this:

     let formGroup = this.fb.group({
          name: [{value: { name: 'Mary' } , disabled: false}, [Validators.required]],
          age: ['', [Validators.required]],
        });
    

    stackblitz

    0 讨论(0)
提交回复
热议问题