Within my component, I have declared the variable "countries$":
countries$!: Observable<Country[]>;
To populate this variable with data from this API, I use the following code in the "ngOnInit" lifecycle hook:
ngOnInit(){
this.countries$ = this.apiService.getAllCountries();
}
In order to display the data in the HTML template, I utilize the following syntax:
<div>
<app-country-card *ngFor="let country of countries$ | async" [country]="country"></app-country-card>
</div>
I aim to add a search feature that dynamically filters the list based on user input.
Initially, I attempted to implement this functionality using the "filter" function within a pipe as shown below:
searchFilterCountries(searchTerm: string){
this.countries$.pipe(filter((country: any) =>
country.name.common.toLowerCase().includes(searchTerm.toLowerCase())))
}
The corresponding input field is incorporated into the HTML template like so:
<input type="text" class="form-control" (input)="searchFilterCountries($event.target.value)"/>
Unfortunately, this approach did not yield the desired outcome and triggered TypeScript errors:
Object is possibly 'null'.ngtsc(2531)
Property 'value' does not exist on type 'EventTarget'.ngtsc(2339)
Subsequently, I referenced a filtered list example using Material UI at the following link:
https://material.angular.io/components/autocomplete/examples (The FILTER one)
My attempt to replicate this resulted in the following code snippet:
export class HomeComponent {
countries$!: Observable<Country[]>;
myControl = new FormControl('');
constructor(private apiService: ApiService) { }
ngOnInit(){
this.countries$ = this.apiService.getAllCountries();
}
private _filter(value: string): Observable<Country[]> {
const filterValue = value.toLowerCase();
return this.countries$.pipe(filter(option =>
option.name.common.toLowerCase().includes(filterValue)));
}
}
However, I encountered issues due to dealing with observables instead of the actual data inside them.
An error was detected under the "name" property within "option.name.common", stating:
option.name.common TS error
Property 'name' does not exist on type 'Country[]'
Although modifying the code to access the first element resolved the error temporarily, it reduced the searching capabilities:
option => option[0].name.common.toLowerCase().includes(filterValue)))
Seeking guidance on the utilization of correct operators and resolving TypeScript errors, I questioned if employing operators like mergeMap or switchMap would provide a solution. Additionally, I pondered the effectiveness of rectifying TypeScript errors and whether the implemented approach was fundamentally flawed. Any assistance in refining this functionality would be greatly appreciated.
Can someone assist me in overcoming these challenges?