简体   繁体   中英

Angular 8 Mat-Autocomplete inside ngFor just showing on the last item


I'm doing a custom form with a FormArray in Angular 8 and in every position i have an Autocomplete as an Input, but the behavior is not what i expected. It just shows up on the las position input.

Code:

 <div formArrayName="assignments" *ngFor="let item of myForm.get('assignments')['controls']; let i = index;"> <ng-container [formGroupName]="i"> <div fxLayout="row" fxLayout.lt-md="column" fxLayoutGap="10px"> <mat-form-field fxFlex="30"> <mat-label>{{ 'product.providers.txt.provider' | translate}}</mat-label> <input type="text" matInput formControlName="id_provider"[matAutocomplete]="providers"> <mat-autocomplete #providers="matAutocomplete" [displayWith]="displayPv"> <mat-option *ngFor="let option of filteredOptions[i] | async" [value]="option.id"> {{option.provider_business_name}} </mat-option> </mat-autocomplete> </mat-form-field> </div> </ng-container> </div>

Here is an example:

文本

Since i was receiving the data from an API, i wasn't adding the control on each loop, here is how i solved it!

setExistingAssignments(assignmentsSet) {
        const control = this.myForm.get('assignments') as FormArray;

        assignmentsSet.forEach(s => {
            control.push(this.fb.group({
                // Some assignaments
            }));
            this.ManageNameControl(control.length - 1); // This is the function
        });

        this.available = true;
        return control;
    }

// The function
ManageNameControl(index: number) {
        const arrayControl = this.myForm.get('assignments') as FormArray;

        if (arrayControl.length > 0) {
            this.filteredOptions[index] = arrayControl.at(index).get('id_provider').valueChanges
                .pipe(
                    startWith<string>(''),
                    map(value => typeof value === 'string' ? value : value['id_provider']),
                    map(name => name ? this._filter(name, 'provider') : this.options.slice())
                );
        }

    }

So the function before was outside the loop! Now it's inside so on each position it will add a control and a search for that row!

Thank you very much!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM