I used autocomplete angular material to list options loaded from REST API but my list shows nothing and is empty but after starting typing it shows the list.
I used getData()
function to fetch data from API and fill options
array but I think the list won't fill because options
is an array and filteredOptions
is and observable and filteredOptions
will fill later. I don't know how to fix it.
I expected to see the list when I click on input field but it is empty.
Here is my codes:
html:
<form >
<mat-form-field appearance="fill">
<mat-label>Number</mat-label>
<input type="text"
placeholder="Pick one"
aria-label="Number"
matInput
[formControl]="myControl"
[matAutocomplete]="auto">
<mat-autocomplete autoActiveFirstOption #auto="matAutocomplete">
<mat-option *ngFor="let option of filteredOptions | async" [value]="option">
{{option}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</form>
.ts file:
import { Component, OnInit} from '@angular/core';
import { FormControl} from '@angular/forms';
import { Observable } from 'rxjs';
import { map, startWith} from 'rxjs/operators';
import { AuthenticationService, Products_Header_VW } from '...';
@Component({
selector: 'app-test-second',
templateUrl: './test-second.component.html',
styleUrls: ['./test-second.component.scss']
})
export class TestSecondComponent implements OnInit {
myControl = new FormControl('');
options: string[] = [];
filteredOptions!: Observable<any>;
constructor(private auth: AuthenticationService) {
this.getData().subscribe(x => {
this.options = x;
});
}
ngOnInit() {
this.filteredOptions = this.myControl.valueChanges.pipe(
startWith(''),
map(value => this._filter(value || '')),
);
}
private _filter(value: string): string[] {
const filterValue = value;
return this.options.filter(option => option.includes(filterValue));
}
//**** Get all product data and move it to a string ****
private getData(): Observable<string[]> {
return this.auth.getallproductheadersvw()
.pipe(
map(
x => x.data.map((y:Products_Header_VW) => y.Product_Title_Persian)
)
)
}
}
Thank you for your attentions.
CodePudding user response:
if you try to remove filter to verify all data and after applying the filter to exclude all items starttwith ''''
CodePudding user response:
I subscribed filteredOptions
inside getData().subscribe()
. So filteredOptions
executed after getData
completed and problem solved.
ngOnInit() {
this.getData().subscribe(x => {
this.options = x;
this.filteredOptions = this.myControl.valueChanges.pipe(
startWith(''),
map(value => this._filter(value || '')),
);
});
}
I think I could use concat
operator too.