Search code examples
angularangular-materialangular7angular-reactive-formsangular-forms

Nested Input Search in Table in Angular Reactive Forms


I have a very simple problem that i can't fix it. I just need the autocomplete input in the table to function.

Pls see this stackblitz link

onSelectProduct(val: string) {
    this.filteredOptions = this.form.get("products").valueChanges.pipe(
      startWith(""),
      map(value => this._filter(value))
    );
  }

  private _filter(value: string): string[] {
    console.log(value);
    const filterValue = value.toLowerCase();
    return this.options.filter(
      option => option.toLowerCase().indexOf(filterValue) === 0
    );
  }

Solution

  • In order to fix the autocomplete you need to init the variable called filteredOptions.

    Init that variable on the constructor. And take your value written into the input on the filter function.

    constructor() {
     // .. code omitted
     this.initFilteredOptionsByIndex(0);
    }
    
    initFilteredOptionsByIndex(index: number) {
      this.filteredOptions = this.form.get("products").valueChanges.pipe(
        startWith(""),
        map(value => this._filter(value, index))
      );
    }
    
    onFocus(index: number) {
     // I use input focus to get each row index
     this.initFilteredOptionsByIndex(index);
    }
    
    private _filter(value: any, index: number): string[] {
      if (!value) {
        return [];
      }
    
      const filterValue = value[index].product_id.toLowerCase();
    
      return this.options.filter(option => option.toLowerCase().indexOf(filterValue) === 0);
    }
    

    Solution available here.