Discover how to retrieve service response data from an API and populate it into the Select Option with Angular 2

Api.services.ts

 getListOfNames() {
     return this.http.get(this.BaseURL + 'welcome/getnama')
            .pipe(map(response => {
                 return response;
            }));
 }
 

After making the API call, I receive the following response:

{
"status": "OK",
"Output": [
    {
        "id_pemborong": "1569079912",
        "nama": "ayub"
    },
    {
        "id_pemborong": "1569125109",
        "nama": "Hartono"
    },
    {
        "id_pemborong": "1569319859",
        "nama": "agus"
    },
    {
        "id_pemborong": "1569416787",
        "nama": "joko"
    }
   ]
 }

I am looking for guidance on how to bind this response to a Select Option in Angular. Can someone help me with this?

Answer №1

procedure

fetchNames() {
    return this.http.get(this.BaseURL + 'welcome/getnama')
}

next, you should subscribe to it within your component

//declare a variable
NameList:any[]=[];

// replace service with the name of your service
this.service.function.subscribe(data => this.NameList = data);

and in the Template

<select  [(ngModel)]="selected" (change)="onChange($event)">
<option [label] ="name" *ngFor="let item of NameList" [selected]="selected" 
  [value]="name">{{name}}
</option>
</select>

Answer №2

Your map function is not working correctly in your code. To fix this, you should map the response to the Output property and then subscribe to the Observable to retrieve the value.

api.service.ts

listNama() {
    return this.http.get(this.BaseURL + 'welcome/getnama').pipe(
        map(response => response.Output)
    );
}

Next, make sure to subscribe to the Observable in your component:

import ApiService from 'path/to/api/service';
...

    namaList: Nama[];

    constructor(private apiService: ApiService) { }

    ngOnInit() {
        this.service.listNama().subscribe(data => {
            this.namaList = data;
        });
    }

You'll also need to define a type for the data received, which can be done using the Nama interface:

export interface Nama = {
    id_pemborong: string;
    nama: string;
}

Lastly, use the namaList array in your HTML template to display the list in a dropdown menu:

<select>
    <option *ngFor="let item of namaList" [value]="item.id_pemborong">{{item.nama}}</option>
</select>

Answer №3

Ts

    MyNameList:any[]=[];
    displayNames() {
    return this.http.get(this.BaseURL + 'welcome/getnama')
      .pipe(map(response => {
      this.MyNameList= response.Output;
      }));
     }

Html

    <select  [(ngModel)]="selected" (change)="onChange($event)">
       <option [label] ="name" *ngFor="let item of MyNameList" [selected]="selected" [value]="name">
          {{name}}
       </option>
    </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

Remove data from a database using Ajax in ASP.NET MVC without utilizing DataTables

I'm encountering a slight issue with my code. I am attempting to delete a row from the database without using DataTables in ASP.NET MVC, but it seems to be not working as expected. I have displayed all items from the database on a page within div elem ...

TypeScript Redux Thunk: Simplifying State Management

Seeking a deeper understanding of the ThunkDispatch function in TypeScript while working with Redux and thunk. Here is some code I found: // Example of using redux-thunk import { Middleware, Action, AnyAction } from "redux"; export interface ThunkDispatc ...

A guide on leveraging Jest and Typescript to mock a static field within a class

While working with Typescript and a third-party library, I encountered an issue trying to write unit tests that mock out the library. Here's an example scenario: // Library.ts // Simulating a third party library export class Library { static code ...

What is the reason buttons in mat-menus do not submit?

I have implemented a mat-menu to showcase a list of choices for the user. The objective is to trigger the submission of my formGroup when a user selects an option from the menu. dropdown.component.html <form [formGroup]="myForm" (ngSubmit)=onSubmit(my ...

What is the best way to send a function along with personalized data?

Currently, I am working on a project using node.js with socket.io. I am looking for a way to have socket.on() use a unique callback function for each client that joins the server. Here is my current technique: I have created a simple JavaScript class whi ...

AngularJS validation for minimum character count prevents character overflow

Encountering an unusual "issue". I've set up a form with a textarea that has both a minlength and maxlength validation. In addition, there's a straightforward character count displayed: <textarea ng-trim="false" ng-model="form.text" minlengt ...

When utilizing the Angular 9 package manager to install a package with the caret (^) in the package.json file, it may

Within my package.json file, I have specified the dependency "@servicestack/client":"^1.0.31". Currently, the most updated version of servicestack is 1.0.48. On running npm install on my local environment, it consistently installs vers ...

Perform a replacement with jQuery.replaceWith() on an input field and refocus in Microsoft Internet Explorer

There exists a script http://gist.github.com/457324 which establishes default text (extracted from the element's title attribute) for empty input[type=text] as well as input[type=password] elements. However, setting default text for password elemen ...

Run some code and then enter interactive mode

Is there a method to run certain code (from a file or a string) before entering interactive mode in node.js? For instance, if I have script called __preamble__.js with the following content: console.log("preamble executed! poor guy!"); and a user enters ...

Creating dynamic transformations and animations for characters and words within a paragraph in 3D

Looking to add animation effects to specific parts of a paragraph, but transforming the entire box instead. Remembering seeing a solution on StackOverflow before, now regretting not saving it. Spent over an hour searching for a similar answer without succ ...

Using Selenium to interact with a link's href attribute through JavaScript

New to Java and Selenium, I'm facing difficulties when trying to click on a link with JavaScript in href attribute. Here's the snippet from the page source: href="javascript:navigateToDiffTab('https://site_url/medications','Are y ...

Save documents in Firebase storage

Currently in the process of developing a web application using Firebase and Angularjs as my frontend tools. Curious to know whether it's feasible to store various file types within the Firebase DB. Could you shed some light on any potential limitatio ...

What is the process for personalizing the appearance in cdk drag and drop mode?

I have created a small list of characters that are draggable using Cdk Drag Drop. Everything is working well so far! Now, I want to customize the style of the draggable items. I came across .cdk-drag-preview class for styling, which also includes box-shado ...

The dialog box is not taking up the full width of the browser window

I'm facing an issue with a dialog box that only occupies a portion of the browser width, despite having a width set to 100%. The backdrop, however, extends across the entire width. //App.js import React from "react"; import ConfirmationDial ...

Should a checkbox be added prior to the hyperlink?

html tags <ul class="navmore"> <li><a href="link-1">Link 1</a></li> <li><a href="link-2">Link 2</a></li> </ul> Jquery Implementation in the footer $(".navmore li a").each(function(){ v ...

How can I effectively utilize the Metamask SDK with TypeScript?

Currently, I am in the process of developing a webpack+pnpm+typescript+react website. All the versions being used are LTS and my preferred IDE is VSCode. According to the guide provided by Metamask here, it seems like I need to follow these steps: npm i @m ...

Choosing an option in Angular 2 based on a specific condition

My question is about a select element: <select id="position"> <option *ngFor='#contactType of contactTypes' [attr.value]='contactType.contactTypeId'> {{contactType.description}} </option> </select ...

Experiencing difficulties connecting JavaScript with HTML

I'm encountering difficulty with implementing my JavaScript on my website. While it functions properly in this JS Fiddle, I am experiencing issues when trying to use it on my actual site. Below is how I have linked the JS on my site: <head> < ...

I am unfamiliar with this scenario but I can utilize Axios, async/await, and TypeScript to navigate it

Having trouble creating a workflows list from an axios response Error: Argument of type 'Promise<unknown>' is not assignable to parameter of type 'SetStateAction<WorkflowForReactFlowProps[] | null>'. Here's the Axios c ...

Enhancing DOM Elements in a React Application Using TypeScript and Styled-Components with Click Event

I've been working on an app using React, Typescript, and styled components (still a beginner with typescript and styled components). I'm trying to create a simple click event that toggles between which of the two child components is visible insid ...