Utilizing Arrays in Typescript within the Angular Framework

I have developed a Rest API that provides data to populate two drop-down lists in a form. The information retrieved from the API is grabbed by the Angular backend and assigned to the respective drop-downs. Rather than making separate Get requests for each form, I attempted to fetch all necessary data with a single Get request.

Here is an example of a Java Back-end Get method:

@GetMapping("/flight/formdata")
public List getWebSiteFormData() {

    List formDataSet = FligthtDataServices.getWebSiteFormData();
    return formDataSet;
}

The set of data displayed on Postman looks like this:

[
    [
        "London Heathrow",
        "AP"
    ],
    [
        "Velana International Airport",
        "AP"
    ],
    [
        "Hamad International Airport",
        "AP"
    ],
    [
        "Suvarnabhumi Airport",
        "AP"
    ],
    [
        "Changi Airport",
        "AP"
    ],
    [
        "Business",
        "CL"
    ],
    [
        "Premium Economy",
        "CL"
    ],
    [
        "Economy",
        "CL"
    ]
]

In the Service class, we have the following code snippet:

getWebSiteFormData():Observable<any>{
return this.http.get(`${this.baseUrl}/formdata`);
}

My strategy involves binding arrays with 'AP' values to Departure Airports drop-down and those with 'CL' values to Class drop-down. To achieve this, I separated the data into two arrays using identifiers fromAirportList=[]; and flightClass=[];.

The Booking Component is illustrated below:

export class BookingComponent implements OnInit {
  
  public websiteFormData=[];
  public flightClass=[];
  public fromAirportList=[];

  constructor(private flightService:FlightService, private router: Router) { }
  
  ngOnInit(): void {
    this.loadFormData();
  }

  loadFormData(){
    this.flightService.getWebSiteFormData().subscribe(data=>this.websiteFormData=data,error=>console.error(error)) 
   
   for (let item of this.websiteFormData) {
     if(item[1]=='AP'){
       this.fromAirportList.push(item[0]);
     }   
   } 
   console.log(this.fromAirportList)
  }
}

The Booking.component.html file contains the HTML structure for the drop-down displays.

<td style="height: 39px; width: 14%;"> 
    <div class="input-group">
    <div class="input-group-prepend">
      <div class="input-group-text">Departure</div>
    </div>
    <select class="form-control" id="classtype" name="classtype" [(ngModel)]="booking.classtype">
    <option>{{fromAirportList[0]}}</option>
    <option>{{fromAirportList[1]}}</option>
    <option>{{fromAirportList[2]}}</option>
    </select>
    </div>
</td>

Despite my efforts, the drop-down remains empty as seen in the provided image. Your suggestions for correcting this issue would be greatly appreciated.

Answer №1

Start by utilizing the *ngFor directive:

<option *ngFor="let option of fromairportlist">{{ option }}</option>

This approach can prove to be quite beneficial Read more about setting selected options in Dropdown with Angular 4

Answer №2

When dealing with a string array as your result, it is recommended to iterate through it using a for loop. Here is a simple example:

<select>
  <option *ngFor="let item of fromairportlist">{{item}}</option>
</select>

If you have any uncertainties, feel free to check out the solution on stackblitz for reference. https://stackblitz.com/edit/angular-abc123

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

angular ag-grid error with cell editing

I am encountering issues with updating a cell in ag-grid within my Angular 8 application. Below is the code snippet for reference: this.columns = [ { headerName: '', field: 'enabled', width: 30, headerCheckboxSelection: true, check ...

Before loading a deep link, use pre-CanActivate or pre-CanLoad

In my current project, I am faced with a challenging task of transitioning from Adobe Flash & Flex applications on a ColdFusion 11 backend to Angular applications. The expectation is that users will already be logged in and have an active session before a ...

transmit URL parameters to Express using Angular 2

I have implemented an Angular service to retrieve data from Express: getRestaurants(districtId) : Observable<void[]>{ let params: URLSearchParams = new URLSearchParams(); params.set('id', districtId); return this.http.get(this.url, ...

VSCode is unable to locate the typeRoots type declarations

I have organized all the type definitions that will be used in my application into a single file. I created a folder named @types and an index.d.ts file that exports every interface/type needed. I updated my tsconfig.json to include the @types folder: { ...

You cannot assign type 'Node | null' to type 'Node' when attempting to loop through HTML elements in TypeScript

In my code, I am taking a raw Markdown string stored in 'markdownString' and using the marked.js library to convert it to HTML for display on a web browser. My goal is to extract all plain text values from the page and store them in an array of s ...

Leverage properties within the storybook component template

When utilizing a class component in a narrative, it allows you to transmit properties as arguments: const Template: Story<MyComponent> = (args) => ({ props: args, component: MyComponent, }) export const Default = Template.bind({}); export co ...

Best practices for utilizing multiple transactions within a single class

Currently, I am utilizing Spring Boot and leveraging the @Transactional annotation to enforce transactions on a method. Occasionally, I encounter scenarios where I require a method to utilize two or more transactions simultaneously. The straightforward ap ...

I am confused about the term "can only be default-imported using the 'esModuleInterop' flag", could you explain it to me?

I ran into a puzzling error: lib/app.ts:1:8 - error TS1259: Module '"mongoose-sequence"' can only be default-imported using the 'esModuleInterop' flag and it seems to be related to this line of code: import _ from 'mongoose-sequ ...

What is the best way to assign a value to an option element for ordering purposes?

My select element is being populated with fruits from a database, using the following code: <select name="fruitsOption" id="fruitsOptionId" ngModel #fruitRef="ngModel"> <option *ngFor="let fruit of fruits">{{fruit}}</option> </selec ...

Typescript is experiencing an error due to the use of attr("disabled", false) causing a disruption

Within my ts file, I'm using the code snippet below: $('input[type=hidden]').attr("disabled", false); The code functions as intended, however, an error persists: Argument of type 'false' is not assignable to parameter of typ ...

Is there a way to configure the currency symbols in App.module for GYD (Guyana Dollar) since the Angular Currency Pipe Symbol is not available for it

<h1> My current rate is : {{'202' | currency:'GYD'}}</h1>` The current output displays as: GYD 202 However, the expected output should be: GY$ 202 ...

Issue with accessing undefined property in Angular 2+ using Typescript

In my Angular 7 project, I am retrieving data from a service which looks like this: {name: "peter", datetime: 1557996975991} I have a method that is supposed to retrieve this data: myMethod() { this.myService.getdata().subscribe((res) = ...

Mocking a named class-export in TypeScript using Jest

I have a node module that exports several classes, including one called Client, which I utilize to create clients with various APIs as methods. I'm currently attempting to test my module, which has a dependency on this node module, using Jest. Howeve ...

Is it possible to swap images by clicking on them?

Let's say I'm working with 3 images. Image A, B and C. A is the main image initially. If I click on image B, it will become the main image and image A will take its place in the old position. The same condition applies when B is the main image a ...

How to use the route.navigate() method in Angular 9 to open a URL in a new tab with a query string

When a button is clicked within a table in our application, I have to open a new tab with details of a specific record from the table. Currently, the code I am using navigates to a new URL and uses resolvers to fetch data from the backend on the new page. ...

Utilizing AngularFirestore to fetch a reference to a document within a collection and associate it with a specific class model

I'm exploring ways to merge two Firestore collections that are connected through a reference field. These are the two collections in question: https://i.sstatic.net/ARGHs.png In my userstory template, I aim to showcase the displayName of the referen ...

Passing data from an AJAX post request to a Spring controller

I am encountering an issue when attempting to send data from a table using ajax post requests. The values from each td element are being sent with strange characters, and I am uncertain about the correct way to send these values. Below is the ajax request ...

Generate an instance containing attributes that correspond to constant string values within a class

In the world of TypeScript, I have a scenario that might be a bit tricky, but I'll throw it out there anyway. Let's say I start with a base service class: export default class Service { public static readonly accessorName: string constructo ...

Having trouble retrieving data from a JSON file within an Angular application when utilizing Angular services

This JSON file contains information about various moods and music playlists. {mood: [ { "id":"1", "text": "Annoyed", "cols": 1, "rows": 2, "color": "lightgree ...

The issue with Angular 2's Ng style is that it does not properly remove the old style when there is a change

I am currently experiencing an issue within my project. When assigning an object to ngStyle in a div, the problem arises where ngStyle does not clear the style properties from the previous object when there is a change in the object. It should ideally rem ...