Guide to dynamically loading mat-options with values retrieved from an API array

I seem to be facing an issue as I am unable to populate the md-option with the data retrieved from an API. It feels like there might be something missing in my code.

Below is the service.ts file where I make the API call and attempt to fetch the data:

getCars(){
 this.http.get(this.rootURL+'/car/getallcars')
 .toPromise()
 .then(res => this.carList = res as Cars[]);
}

This is how the API response looks like:

{
"id": "b49981fc-730e-49fc-b5e4-0159f4b42c9d",
"brand": "Mercedes",
"model": "G-Klasse",
"mileage": 19000,
"isAvailable": true
}

In my HTML file, it's structured like this:

<mat-form-field appearance="fill">
<mat-label>Field</mat-label>
<mat-select name="myField"  #brand="ngModel [(ngModel)]="service.formData.brand">
<mat-option *ngFor ="let car of carList" [value]="car.id" >{{car.brand}}</mat-option>
</mat-select>

The challenge lies in figuring out how to correctly fetch the elements from the API within the component.ts file in order to populate the mat-option successfully.

Answer №1

Could you please test the code provided below?

To update your service.ts file, replace the following code:

getCars(){
  return this.http.get(this.rootURL+'/car/getallcars');
}

In your component.ts file

ngOnInit() {
    if (!this.service.formData) {
        this.resetForm();
    }
    this.fetchCarData();
}

cars: any = [];
fetchCarData(): void{
    this.service.getCars().subscribe(data => {
       console.log(data);
       this.cars = data;
    });
}

Then in your component.html file

<mat-label>Field</mat-label>
<mat-select name="myField" #brand="ngModel [(ngModel)]"="service.formData.brand">
  <mat-option *ngFor="let car of cars" [value]="car.id">{{car.brand}}</mat-option>
</mat-select>

Answer №2

you have the potential to achieve it in this manner

  • construct a class named Vehicle
export class Vehicle {
 id: string,
 brand: string, 
 model: string,
 mileage: number,
 isAvailable: boolean
 constructor(data) {
    this.id = data.id;
    this.brand = data.brand;
    this.model =  data.model;
    this.mileage = data.number;
    this.isAvailable = data.isAvailable;
 }
}
  • proceed by importing the class into your service and utilizing it.
getCars(){
 this.http.get(this.rootURL+'/car/getallcars')
 .toPromise()
 .then(res => {
     this.carList = res.data.map(car => new Vehicle(car))
  });
}

Answer №3

After reviewing the responses above, I believe there is a more efficient approach. Here's my suggestion:

Start by creating a new interface in your models: car.ts

export interface Car{
 id: string,
 brand: string, 
 model: string,
 mileage: number,
 isAvailable: boolean
}

service.ts:

getCars(): Observable<Car[]> {
  return this.http.get(this.rootURL+'/car/getallcars');
}

component.ts:

import { Car} from 'src/app/shared/model/car';
import { CarService } from 'src/app/shared/service/car.service.ts';

export class CarComponent implements OnInit {
 

    cars: Car[];
    selected: string;

    constructor(private carservice: CarService) { }  

    ngOnInit(): void {
       this.carService.getCars().subscribe(data => {
         this.cars = data;
      })
     }

}

Include the following code in your template:

<mat-form-field appearance="fill">
<mat-label>Field</mat-label>
<mat-select name="myField"  #brand="ngModel [(ngModel)]="selected">
<mat-option *ngFor ="let car of cars" [value]="car.id" >{{car.brand}}</mat-option>
</mat-select>

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

Component not appearing in Storybook during rendering

I'm trying to incorporate the MUI Button Component into my storybook and then dynamically change MUI attributes like variant, color, and disabled status directly from the storybook. While I was successful in doing this with a simple plain HTML button, ...

Tips for retrieving a date and time selection from a mat-date-picker and mat select?

I am currently utilizing Angular calendar to display various events. Each event is defined by the following parameters: event:{ title: string, start: Date, end: Date }; As material design does not offer a date-time picker, I have opted for usi ...

Post-Angular migration (going from version 12 to 14), there are still lingering security risks associated with the "d3-color vulnerable to ReDoS" issue

Following the migration to Angular 14, I made sure to update my "@swimlane/ngx-charts" version to "20.1.2" and the "d3" version to "7.8.4". However, even after running the npm install command, I am still encountering 5 high severity vulnerabilities in my p ...

Update the event listeners for child components

During my transition from Vue2/JavaScript to Vue3/TypeScript, I encountered a difficulty with migrating a computed property that remaps component listeners to child components based on a prefix. In Vue2/JavaScript, the computed property looked like this: i ...

Can you share the appropriate tsconfig.json configuration for a service worker implementation?

Simply put: TypeScript's lib: ['DOM'] does not incorporate Service Worker types, despite @types/service_worker_api indicating otherwise. I have a functional TypeScript service worker. The only issue is that I need to use // @ts-nocheck at t ...

What are the distinctions between manually and programmatically changing URLs in Angular 6?

My query pertains to differentiating navigation methods, specifically between clicking a button with [routerLink] and manually entering a URL in the browser's search bar. Update: I have a fixed menu on a certain page that appears as follows: <ul& ...

Determine which rows have the checkbox enabled and showcase them in a separate table using Angular

I currently have two tables, namely Table1 and Table2. The data in Table1 is fetched from a service and contains columns like Qty, Price, and Checkbox. The Checkbox column consists of checkboxes as values, while Qty and Price columns contain numeric values ...

Guide on linking numerous RX observables and serving as a unified function

Here, I am attempting to implement Angular2 generic http error handling for 401 errors. The goal is to prompt the user to re-enter login details and then retry the http request. The issue arises when the retry function does not work as intended because it ...

Having trouble getting Angular Material's mat-autocomplete to function properly when the application is in

I am currently in the process of incorporating a mat-autocomplete field, following the guidelines provided in the documentation. Everything functions as anticipated when tested on ng serve. However, after running ng build --prod and deploying to Firebase, ...

What is the rationale behind Typescript permitting the assignment of an "any" object type to a class object?

Within my codebase, there is a class object that I have initialized: groupNameData: GroupNameData = new GroupNameData(); In addition, I also have an any object called groupNameDatas. groupNameDatas: any; Experiment 1 (class = any) To experiment with ...

Restrict the keys to only properties that have an array data type

Is there a way to limit the keyof operator to only accept keys of a specified type in TypeScript? interface Data { items: string[]; name: string; } // I want to restrict the keyof operator to only allow keys where the value is of type `F` type Key&l ...

What strategies can be used to prevent circular dependencies within components?

In my application, the root component is named app-document-form and it iterates through the children elements of an object called documentBlock: <ng-container *ngFor="let element of documentBlock?.children"> <!-- This part is crucial -- ...

Determining the height of dynamically rendered child elements in a React application

Looking for a way to dynamically adjust the heights of elements based on other element heights? Struggling with getting references to the "source" objects without ending up in an infinite loop? Here's what I've attempted so far. TimelineData cons ...

Using async/await with mysql2 in Node.js can lead to undefined rows and fields

I am facing an issue where the query below is returning undefined in rows and field even though the user table has data. How can I properly use the promise version in TypeScript? Any help would be greatly appreciated. Thank you... code import mysql from ...

Resetting a Template-Driven form in Angular using programming techniques

Exploring Angular/Typescript as a newcomer with the use of Template-Driven forms in Angular 10. Attempting to reset the form without submitting it or relying on button clicks. Despite researching similar issues, they all entail submitting the form for a re ...

Ways to link information from one entity to another

Currently, I am utilizing the TMDB API to showcase movies along with their respective genres. In my code, I have two objects where I retrieve details for movies and genres as shown below: listTrendingMovies() { this.listMediaService.listTrendingMovie ...

Is there a way to retrieve the requested data in useEffect when using next.js?

As a newcomer to next.js and TypeScript, I am facing an issue with passing props from data retrieved in useEffect. Despite my attempts, including adding 'return scheduleList' in the function, nothing seems to work. useEffect((): (() => void) = ...

Omit the timezone details when initializing a new Date object in Angular

Encountered a problem while testing the following line of code console.log(JSON.stringify(new Date('2016-06-15 10:59:53.5055'))); The result I'm getting is "2016-06-15T08:59:53.505Z", but I was expecting "2016-06-15T10:59:53.505Z" Is ther ...

Issue with the dropdown functionality in an Angular reactive form

I am experiencing an issue with a select dropdown in my Angular project. I have implemented a reactive form, but the dropdown is not functioning as expected and I am unsure of how to resolve this issue. Could someone offer assistance or guidance on how to ...

Commence the list from the lowest point

I am currently working with Ionic 2 and have a list of items: this.firelist = this.dataService.findMessages(this.chatItem).map(items => { this.updateReadMessages(items); return items.reverse(); }); These items are displayed in a list: <ion-con ...