API returned object is undefined for Mat-Autocomplete

36 Views Asked by At

I have written a code for Mat-autocomplete, where the values in the autocomplete are from an API. This API returns in this format

[
    {
        "_id": "62bc7fcc3e184aac493ad519",
        "name": "Mike Austin",
        "email": "[email protected]",
        "role": "Account Manager"
    },
    {
        "_id": "62bc840a3e184aac493ad51b",
        "name": "Mitch Sawyer",
        "email": "[email protected]",
        "role": "Account Manager"
    }
]

I want to dispaly the name, while taking the internal value as _id.

My code goes something like this:

export interface AccountRepData {
    _id: string,
    name: string,
    email: string,
    role: string
}
wellForm: FormGroup;
accountReps: AccountRepData[];
filteredAccountReps: any[];
...
...

constructor(private fb: FormBuilder, private wellsTableService: WellsTableService) {
    this.wellForm = this.fb.group({
        accountRep: new FormControl('', Validators.required)
    });
}
ngOnInit(): void {
    this.products.clear()
    this.wellsTableService.getUsersByRole('Account Manager')
        .subscribe(response => {
            if (response.statusCode === 200 && response.status === 'SUCCESS') {
                this.accountReps = response.result;
                this.accountRepControl.valueChanges.pipe(
                    startWith(''),
                    map(value => this.filterAccountReps(value))
                ).subscribe(filteredAccountReps => {
                    this.filteredAccountReps = filteredAccountReps;
                });
            }
        });
}

filterAccountReps(value: string): any[] {
    const filterValue = value.toLowerCase();
    return this.accountReps.filter(accountRep => accountRep.name.toLowerCase().includes(filterValue));
}

get accountRepControl() {
    return this.wellForm.get('accountRep') as FormControl;
}

displayAccountRep(accountRep: any): string {
    if (accountRep) {
        const matchingAccountRep = this.accountReps.find(rep => rep._id === accountRep._id);
        if (matchingAccountRep) {
            return matchingAccountRep.name;
        }
    }
    return '';
}

And my html block is:

<mat-form-field class="full-width">
    <mat-label>Account Rep ID</mat-label>
        <input type="text" matInput placeholder="Account Rep ID" [formControl]="accountRepControl" [matAutocomplete]="auto">
        <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayAccountRep">
            <mat-option *ngFor="let accountRep of filteredAccountReps" [value]="accountRep._id">
                {{ accountRep.name }}
            </mat-option>
        </mat-autocomplete>
</mat-form-field>

For some reason in the displayAccountRep function the accountReps object is undefined. I think this might be a DOM issue, but I've been trying to figure this out for several hours and couldn't find anything.

Any help would be greatly appreciated.

0

There are 0 best solutions below