After successfully implementing the mat-select-search component with live search functionality by following guides on Angular ngx-mat-select-search Custom Component and the documentation for ngx-mat-select-search, everything was working smoothly until I tried to introduce dynamic data.
In the Child component, an array of objects is retrieved:
@Input() sites: any[];
This array is then accessed by another function within the component:
export class SiteDropdownComponent<T> implements OnInit, OnDestroy, AfterViewInit {
ngOnInit(): void {
// set initial selection
this.siteCtrl.setValue(this.sites[1]);
// load the initial site list
this.filteredSites.next(this.sites.slice());
// listen for search field value changes
this.siteFilterCtrl.valueChanges
.pipe(takeUntil(this.onDestroy))
.subscribe(() => {
this.filterSites();
});}}
The Parent component incorporates the Child component as follows:
<app-site-dropdown [siteCtrl]="sitesForm.get('site')" [sites]="sites" (sel)="changeCoun($event)"></app-site-dropdown>
When providing objects directly like in the AppComponent works fine:
export class AppComponent implements OnInit, AfterViewInit, OnDestroy {
sites: any[] = [
{id: 'item1', name: 'item1'},
{id: 'item2', name: 'item2'},
{id: 'item3', name: 'item3'}
];
However, when attempting to populate the 'sites' array through a server request with a delay:
getSitesList() {
this.subs.add(this.http.post(this.count, 'url/listSites').subscribe(data => {
this.sites = data.sites;
console.log(this.sites);
}));
An issue arises during the delay time where the SiteDropdownComponent renders before the 'sites' array is populated, resulting in errors such as 'sites are undefined' when trying to use functions that rely on 'sites':
ngOnInit() {
// set initial selection
this.siteCtrl.setValue(this.sites[1]);
// load the initial site list
this.filteredSites.next(this.sites.slice());
}
Is there a more optimal way or function to address this issue? Considering calling these functions at another point in the code, without resorting to using setTimeOut(). A detailed explanation of the SiteDropdownComponent can be found in the provided link above.