The mat-select-search fails to display the initial list upon loading

I am currently implementing mat-select-search using this example. I am utilizing reactive forms with dynamic data where my server's response is just an array of items. The issue I am facing is that when I type in the search, it works fine but the initial list does not show up. How can I ensure that my dynamic data is displayed for the first time?

.ts

vehicles = [];
  public filteredOptions: ReplaySubject<any[]> = new ReplaySubject<any[]>(1);
  protected _onDestroy = new Subject<void>();
  @Output() onSelectionChange: EventEmitter<any> = new EventEmitter<any>();

public modelFilterCtrl: FormControl = new FormControl();

   @ViewChild('multiSelect', { static: true }) multiSelect: MatSelect;
  ngOnInit(): void {
    this.campaignService.getVehicles().subscribe((data: any[])=>{
      this.vehicles = data;
    })

    this.modelFilterCtrl.valueChanges
    .pipe(takeUntil(this._onDestroy))
    .subscribe(() => {
      this.filterEntities();
    });

}

set data(data: any[]) {
    this._data = data;
    // load the initial list
    this.filteredOptions.next(this.data.slice());
  }
  get data(): any[] {
    return this._data;
  }
  private _data: any[];

  ngAfterViewInit(): void {
    this.setInitialValue();
  }

  onChange($event) {
    this.onSelectionChange.emit($event);
  }

  private setInitialValue() {
    this.filteredOptions
      .pipe(take(1), takeUntil(this._onDestroy))
      .subscribe(() => {
        if (this.multiSelect)
          this.multiSelect.compareWith = (a: any, b: any) => a === b;
      });
  }

.html

<mat-select multiple formControlName="Brand" (selectionChange)="onChange($event)" #multiSelect>
      <mat-option>
        <ngx-mat-select-search
        [formControl]="modelFilterCtrl"
        [placeholderLabel]="'Search...'">
      </ngx-mat-select-search>
      </mat-option>
      <mat-option *ngFor="let item of filteredOptions | async" [value]="item">{{item}}</mat-option>
    </mat-select>

Answer №1

It is important to set up the filteredOptions variable when you first retrieve the list of vehicles:

ngOnInit(): void {
    this.carService.getVehicleList().subscribe((data: any[])=>{
      this.vehicleList = data;
      this.filteredOptions.next(this.vehicleList);
    })

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The CSS properties intended for ion-button elements are not taking effect

I'm attempting to set a background color when a ion-button is clicked or maintain the ion-ripple effect after it has filled the button in Ionic 4. I experimented with applying custom CSS states in global.scss, but encountered issues where the active ...

Retrieving the observable's object within the component, excluding the HTML Template

I am currently working on implementing a MATERIAL autocomplete feature for my angular project, taking inspiration from this Stackblitz demo: https://stackblitz.com/run?file=src%2Fapp%2Fautocomplete-overview-example.ts In the demo, they have created an arr ...

The Angular tutorial for the "Tour of Heroes" is experiencing issues with aligning the heroes' list properly

I am currently working on the Angular tour of heroes tutorial. However, I am facing an issue when trying to display the list of heroes as it appears like this: https://i.sstatic.net/AGnzJ.png It is strange because even though the CSS/HTML/TS code from the ...

When using VSCode, Prettier, and TSLint together, enabling the 'formatOnSave' option can interfere with the automatic

As I develop React applications using TypeScript in VSCode, I rely on tools like prettier and TSLint to maintain clean code. In some recent projects, I've noticed that when I save my files, prettier disrupts the automatic sorting of imports: Before ...

Is it possible to load a script conditionally in Angular 2 using the Angular CLI

Is it possible to conditionally load scripts using Angular CLI? I am looking to dynamically load a script in this file based on the environment or a variable. For example, I want to load a specific script in production but not in development. How can I ac ...

POST request doesn't have successful model binding

I'm currently working on an ASP.Net Core 2.0 project which serves as a web api with the client-side implemented using Angular 4. However, I am facing an issue where whenever I post form data from my Angular service to the API, the model properties on ...

Angular CLI build/serve/test commands task problem matcher in VS Code

In an attempt to set up VS code tasks for Angular CLI commands such as 'ng build', 'ng serve', and 'ng test', I want to generate a list of problems that can be easily navigated when running a CLI command. Currently, I execute ...

Can a type guard be implemented to verify if an object field is undefined?

Looking for a way to create typings for the code I am working on. Let's say I have the following interfaces: interface Car { id: string; type: number ownerId: number | undefined; // ... other fields } interface Plane { id: number; ...

Looking to leverage RxJs 6 GroupBy for stream organization? Interested in consolidating emissions from various Grouped Observables?

Input Observable stream: The information is retrieved from an observable stream, which stems from a REST request for various projects. This data is obtained in the form of Observable<Project[]>. const project1: Project = { id: 1, ...

Injecting dynamic components into the root of an Angular2 application

Seeking Solution I am exploring the most effective method to insert a pre-defined component into the main structure of an application and apply @Input() options to that component. Necessity This is essential for developing features like modals/tooltips ...

NativeScript app is functioning properly on the emulator but is experiencing crashes when running on a physical NS7 Angular10 device

Since updating to NativeScript 7 and Angular 10, my app runs smoothly on xCode emulators but crashes immediately after launching on a real device (specifically, iPhone 10 with iOS14). Below is the crash report from TestFlight: Date/Time: 2020-09 ...

What is the reason for the Enter key being assigned to the incorrect button?

In my Angular 13 form, there are several buttons. One of them is used to add a new row to the form: <div class="col-md-2 offset-md-8"> <button class="badge rounded-pill bg-secondary mt-2" (click)="addRow()& ...

The type 'true | CallableFunction' does not have any callable constituents

The error message in full: This expression is not callable. No constituent of type 'true | CallableFunction' is callable Here is the portion of code causing the error: public static base( text, callB: boolean | CallableFunction = false ...

Is it possible to effectively iterate through an Angular service request?

Can you help me troubleshoot this code to ensure it runs smoothly? onSubmit() { let pdfData = [ { field_name: 'data.Date', value: this.freshDeskData.date, placeholder: '', page_no: 1, }, ...

Is it possible to utilize the 'any' data type in a fetch request in typescript

Encountering an issue where the fetch function in this code snippet is causing a typescript warning: const fetcher = (...args: any) => fetch(...args).then((res) => res.json()); Why does using fetch(...args:any) not resolve the warning? Any suggestio ...

Tips for aligning flex items based on the previous item in a flex container

Place 'text1' beneath the number 1 (so that the 't' character is under the 1), and 'text2' beneath the number 5 (with the '2' character under the number 5) This should be done dynamically to adjust to a varying numb ...

What is the process for transferring data from child components to parent components in Angular 2?

I have been thinking about the scenario where a descendant of a descendant of a parent needs to pass information back up to the parent. Would the descendant passing the information need to go through the chain back up? Descendant2 Component -> Descenda ...

The error message "Property '...' is not found on the type 'ServerContextJSONValue'" pops up whenever I try to utilize the useContext() function

After creating a Provider and defining the type, I encountered a TypeScript error when using it with useContext(): "Property '...' does not exist on type 'ServerContextJSONValue'. I'm not sure what I am missing. Can anyone help me ...

Angular 4.2.5: Harnessing the Power of HTTP Interceptor

Noop Interceptor import {Injectable} from '@angular/core'; import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/http'; @Injectable() export class NoopInterceptor implements HttpInterceptor { intercept(req: Ht ...

When using the `create-react-app` command with the `--typescript` flag, you may encounter an issue when attempting to compile namespaces with the `--

I started a project using npx create-react-app my-app-ts --typescript, then I added two new files, sw-build.js and sw.js in the src/ directory. The content of these files was taken from the discussion on Workbox guidelines at (Guidlines for Using Workbox) ...