I am currently exploring the usage of Autocomplete from Angular Material.
Instead of having their predefined data as
options: string[] = ['One', 'Two', 'Three'];
, I have my own object.
This is how I retrieve the data from my object, which is stored in a file called currencies.json:
list(): Observable<Currencies> {
return this._http.get('./assets/currencies.json') as unknown as Observable<Currencies>;
}
public currencies$ = this.getAllCurrencies();
getAllCurrencies(): Observable<Currencies> {
return this._currencyService.list();
}
Now, here's my approach to bind the autocomplete functionality:
<ng-container *ngIf="currencies$ | async">
<mat-form-field appearance="fill">
<mat-label>Currency</mat-label>
<input id="currency" type="text" matInput placeholder="Select a currency. E.g. USD" [matAutocomplete]="auto" formControlName="currency">
<mat-autocomplete autoActiveFirstOption #auto="matAutocomplete">
<mat-option *ngFor="let currency of currencies$ | keyvalue" [value]="currency.key">
{{currency.key}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</ng-container>
this.currencies$ = this.formMain.valueChanges.pipe(
startWith(''),
map(value => this.currencies$.subscribe(data => data.currency.includes((value.toString().toUpperCase() || '')))),
);
However, encountering the following error:
TS2322: Type 'Observable' is not assignable to type 'Observable'. Property 'currency' is missing in type 'Subscription' but required in type 'Currencies'.
Any suggestions on how to rectify this issue?
Another attempt was made with the following code:
currencies?: Observable<string[]>;
this.currencies = this.formMain.valueChanges.pipe(
startWith(''),
map(value => this.currencies$.subscribe(data => data.currency.includes((value.toString().toUpperCase() || '')))),
);
But faced the subsequent error:
TS2322: Type 'Observable' is not assignable to type 'Observable
'. Type 'Subscription' is missing the properties from type 'string[]': length, pop, push, concat, and more.
Attempting it without using subscribe()
:
this.formMain.valueChanges.pipe(
startWith(''),
map(value => [this.currencies$].filter(currency => currency.includes(value)))
);
And receiving this error:
TS2339: Property 'includes' does not exist on type 'Observable'.
You can check out my StackBlitz code along with the official Angular Material code on StackBlitz. My objective is to replicate the official code behavior using my custom data.