Utilizing Angular 2's ng-select to retrieve information from a JSON file

I recently integrated the ng-select component into my project to enable an autocomplete feature in a select dropdown.

However, I encountered issues when trying to populate the options of this select from a JSON file!

Here is the part that works:

prodFilterDescr: Array<IOption> = [
        {label: 'Belgium', value: 'Belgium'},
        {label: 'Luxembourg', value: 'Luxembourg'},
        {label: 'Netherlands', value: 'Netherlands'}
    ];

Html:

        ...<ng-select
                [options]="prodFilterDescr"
                placeholder="Prodotto"
        >
        </ng-select>...

The following part doesn't work (within the constructor):

        this.http.get('app/json/filtriProdotti.json')
        .subscribe(res => this.filters = res.json());
        var filter = [];
        this.filters.forEach(function(item){
            filter.push(item.tipoProdottoId)
        })  
        console.log(filter)   
        let typeProdFilter: Array<IOption> = filter;
        console.log(typeProdFilter) 

Html:

            <ng-select
                    [options]="typeProdFilter"

                    placeholder="Tipo prodotto"
            >
            </ng-select>

I'm having trouble getting my "options" to successfully read the data from my JSON file. How can I resolve this issue?

Answer №1

The issue at hand involves the use of the async call with the http.get method.

Here is a code snippet to address the problem:

// Define this outside of the constructor
typeProdFilter: Array<IOption>;

// Keep this inside the constructor
this.http.get('app/json/filtriProdotti.json')
.subscribe(res =>
{
    this.filters = res.json()
    var filter = [];
    this.filters.forEach(function(item){
        filter.push(item.tipoProdottoId)
    })  
    console.log(filter)   
    this.typeProdFilter = filter;
    console.log(this.typeProdFilter)
});

If you want to dynamically load options, please refer to the following link:

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

Running ng build --prod does not compile the source code

Upon running the following command: ng build --prod utilizing the following versions: node version: v6.11.0 @angular/cli: 1.0.0-rc.2 typescript: Version 2.4.2 encountered errors as shown below: ERROR in ./src/main.ts Module not found: Error: Can ...

Exploring the Relationship Between CSS Attribute Values and Strings in Eclipse

Looking to conduct a test to determine whether the value of a CSS attribute matches a specific string. The comparison functions correctly in JSFiddle, providing the expected result. However, Eclipse presents a different outcome and appears to interpret the ...

Discover and transform any strings that begin with http & https into clickable links

Can I use jQuery to search a paragraph for all strings that begin with http & https and turn them into clickable links? I have my Twitter feed displayed on my website, but any lines starting with http & https are shown as regular text. Is it feasible to t ...

Numerous occurrences of a jQuery plugin

This plugin is a basic carousel slider. It functions correctly when there is only one instance of the class on the page, but when multiple instances are present, they all move simultaneously regardless of which previous/next button is clicked. I am having ...

The error message stating that 'children' property is missing in the 'IntrinsicAttributes' type is displayed

I'm attempting to convert my code from pure JavaScript to TypeScript. export const Container = ({ as: Element = 'div', children, className, ...rest }) => { return ( <Element {...rest} classNa ...

How to download a file using AJAX in Laravel?

Is there a way to download a CSV file within an ajax call? I have an ajax request in my Laravel controller that successfully retrieves the file contents in the response. However, I am facing issues with actually downloading the file. Laravel controller c ...

What is the process for initiating a Fargate task once a database instance has been successfully provisioned using AWS CDK

I am currently working on an AWS CDK stack that involves creating a Fargate task (using ApplicationLoadBalancedFargateService) from a docker container. The container houses a web application that needs to connect to a database. Upon deploying the CDK stack ...

Enhancing images by creating clickable sections in a more organized and efficient manner

Are there any other methods to make parts of an image clickable in a more organized way, aside from using the coordinates method or directly embedding images from Photoshop? <script> new el_teacher = ["candice","john"]; $(".teacher1").mouseenter(fu ...

"How can I extract father's details by clicking on a button

After clicking, I need to access the parent element. Here is the HTML code I have: <button mat-icon-button (click)="download($event)"> The generated HTML code is as follows: <button _ngcontent-wsc-c153="" mat-icon-button=&q ...

Using Jquery ajax within a function

$(function () { $("#rv-title").click(function(event) { $("#rv-content").toggle(); $.ajax({ url: 'index.php?route=check', dataType: 'json', success: function(json) { if (json['output& ...

Nesting *ngFor in Angular allows for a powerful way

I have a table that contains two nested iterations. The first three columns iterate through an array of objects (items), while the fourth column should iterate through an array of numbers (total=[30,70,100]). <table class="table"> <thead cla ...

Is there a way to determine which radio button has been chosen using jQuery?

I'm trying to retrieve the value of the selected radio button using jQuery. Can anyone help with this? Currently, I am able to target all radio buttons like so: $("form :radio") But how can I determine which one is actually selected? ...

How can I ensure the ng-click function waits for the completion of a jQuery script before running?

I am facing a problem where I need to empty out a ul list of existing items before initiating a REST call to Flickr's API to populate it with 20 new items. Currently, both actions are happening simultaneously resulting in the list remaining empty desp ...

Issue with Angular5: Spinner malfunctioning during initialization of the page

My service emits two events dataLoaded and loadingData. I want to display a GIF image when data is loading and hide it when data is loaded. In the component, I handle both events and update a Boolean variable accordingly. However, on the initial page load, ...

- #hashtag navigation error in Chrome: successfully jumps to certain sections, but not all

I've been racking my brain trying to identify the root cause of a frustrating glitch. When visiting http://apapartnership.com/vol3 and clicking on any of the #hash links in the table of contents, strange results occur: 1. Clicking on any 'chapte ...

Unable to access 'export default class extends Vue' in the template

I've recently started using Vue.js with TypeScript, but I'm having trouble accessing values from outside the class. @Component({ name: 'SidebarItem', components: { SidebarItemLink } }) export default class extends ...

The Angular application is configured with distinct locales for debugging and for running

In my application, there is a calendar feature that displays a string representation of a timestamp. When selecting a date from a date picker (using date-fns and angular-calendar), I make a POST request in my service. postWorkingSlot(workingSlot: NewWorkin ...

Guide to displaying the continent name on a 3D globe using Reactjs, TypeScript, and Threejs

I am currently working on integrating Threejs into my Nextjs 14 application to create a 3D earth globe using Gltf. However, I am facing an issue where I am unable to display the text of the continent name on their respective continents. I want to have fixe ...

Remove HTML tags from a table cell containing a combination of radio buttons and labels

Javascript Function: My JavaScript function posted below is designed to iterate through the column indexes specified in the 2nd parameter and also iterate through the element ids provided in the 3rd parameter. It will then populate the textbox, radiobutto ...

Ways to ensure that the dropdown content remains visible even after the mouse has exited the trigger element

There are three buttons arranged in a row, and when one is hovered over, dropdown content appears underneath all three buttons. However, the content disappears when the mouse moves down to it. Unfortunately, images cannot be posted inside yet** https://i.s ...