Saving JSON data into an array in Angular with TypeScript can be accomplished by creating

Currently, I am encountering an issue while utilizing the Angular mention library.

Below is the typescript code I am working with:

items: Object[] = ["jay","roy","gini","rock","joy","kiya"];

I am utilizing the array named items in my component.html file

<input  type="text" id="cname" name="cname" placeholder="Type  Here.." [mention]="items">

When typing in the text box, the library provides suggestions based on the typed characters. For example, typing @j will suggest names starting with j and inserting them with the @ sign. This feature allows for auto searching through the array, facilitated by importing the mention library into my Angular7 application.

As part of a project where user data is retrieved from a web service, I need to populate the items array with these users.

The JSON data structure is as follows:

 [
   {
      "attributes":  {
        "User": "jay"
    }
},
   {
      "attributes": {
        "User": "roy"
    }
},
    {
      "attributes":{
        "User": "kiya"
    }
},
    {
      "attributes":{
        "User": "gini"
    }
},
   {
      "attributes": {
        "User": "rock"
    }
},
   {
      "attributes": {
        "User": "joy"
    }
}

]

This JSON data retrieved from the web server is stored in a variable and I aim to incorporate it into the items array to enable accurate auto suggestions in the text box.

Despite my attempts, I am currently experiencing issues with the suggestions not appearing while typing in the text box.

Answer №1

If you find yourself needing assistance in mapping the output of your web service to a string array, consider using the following code snippet to achieve the desired result.

Here is an updated solution tailored for the latest JSON format.

this.myWebService.myWebServiceMethod.subscribe(result => {
    this.items = result.map(item => {
        return item.attributes.User;
    }
}

@abd995 points out a possible performance issue with this approach, as it involves looping through the array. Be cautious of how frequently you run the provided code snippet. If your dataset is relatively small, performance should not be a major concern. However, if you are dealing with a large dataset of 5k+ records, it might be worth considering optimizing your API to deliver data in a more user-friendly format that requires less manipulation on the client side.

Answer №2

To make use of the mentionConfig when dealing with an array of objects, specify the field within the object that should serve as the label by setting it as the labelKey in the mention configuration as shown below.

<input type="text" [mention]="items" [mentionConfig]="{ labelKey:'User'}">

Update

Given that the original question now involves an array of objects with nested properties, it is not feasible to utilize mentionConfig because mention is designed to support only a single level of nested properties. For more information, refer to the mention source code here. Additionally, I have reported this issue on github. In such cases, we would need to generate an array of labels from the object array, as demonstrated below.

items = items.map((item) => item.attributes.User);

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

Yes, it's not able to retrieve the value from headlessui combobox

I have encountered an issue while using the Headlessui combobox component in conjunction with Yup. Despite successfully storing the selected value in the selectedMemory state variable, Yup consistently generates a required error message. I seem to be overl ...

Resolving circular dependencies caused by APP_INITIALIZER

My AuthenticationService is responsible for loading the AngularFirestore and is loaded in the RootComponent. All app modules are lazily loaded within the RootComponent (which contains the main router-outlet). However, several sub-modules also load the Ang ...

Fast + Vue3 + VueRouter Lazy Load Routes According to Files

I am currently working on implementing Domain-Driven Design (DDD) to Vue, and the project structure looks like this: src - App - ... - router - index.ts - Dashboard - ... - router - index.ts - ... The goal is for src/App/router/index.ts to ...

Can someone provide guidance on utilizing parentheses in HTML code?

I am facing an issue in my Angular project while using the WordPress API. The problem lies in the API address structure which includes "" like this: <img src="{{importantvideo.better_featured_image.media_details.sizes.["covernews-med ...

Exploring the Angular 4 Cronstrue Idea: Transforming cron syntax into readable strings[From CronJobs to Cronstrue]

Can anyone provide an example of using the cronstrue concept to convert cron expressions into human-readable strings within Angular 4? I am looking for a library or plugin in Angular 4 that can convert cronjob schedule expressions into readable text [cron ...

Troubleshooting the Ng2-Charts Linechart to display all values instead of just the first two

Starting a new Angular application with the Angular-CLI (beta 22.1) has presented an issue when adding test data (5 values) to a chart. The scaling appears incorrect, displaying only the first two values stretched across the entire length of the graph (ref ...

Substitute the existing path with an alternative route

To move to a different route in Angular 2.0, we typically use route.navigate( [ 'routeName' ] ). However, this approach adds the current route to the browser's history. Is there a technique available to substitute the current route in the ...

I recently upgraded my Angular version from 5 to 8, and encountered an unexpected error with the toastr plugin

I recently upgraded my Angular version from 5 to 8 and encountered an issue. Upon starting the server with 'ng serve', I received the following error in the console: Uncaught TypeError: core_1.style is not a function at Object../node_modules/ng ...

What is the reason behind Angular triggering @HostListener as soon as the element begins to appear in the DOM?

I encountered an issue while writing a directive to close an element when a user clicks outside of the host element. The problem seems to be that the @HostListener is triggered immediately once the element is displayed in the DOM. It might not actually be ...

Having trouble extracting information from a JSON link to populate an Angular Material Table

I have successfully implemented the Angular Material Table to display data from a List. Now, I want to fetch data from a JSON URL and populate this list with that data. I've attempted several methods found online to parse the data into the list, but ...

Issue with Pop Up not redirecting correctly after a successful login in Azure AD

I recently integrated Azure AD with my web application. When clicking on the login window, a pop-up appears with the URL . It prompts for the Azure AD username and password. However, after successfully logging in, a code is returned as a parameter but the ...

How can we transfer a value from a parent component class to a child subclass?

In my TypeScript file, there are three classes within a single file. I am attempting to transfer a value from the MainComponent class to the TableContent class. I initially tried using super() inside the TableContent class which did not work, and then att ...

When attempting to send file data in a $http Post request in Angular 8, the Rails API logs show an empty object {}

Using Angular 8 with a Rails 5.2 API I am currently attempting to add an image attachment feature to my Event model in the edit form. I have been following instructions from this specific tutorial Below is a snippet of my TypeScript code: const httpOpti ...

TypeScript overloading error: Anticipated 0 parameters, received 2 instead

I am facing an issue with a class containing an overloaded method that has two versions. One version does not take any arguments, while the second one can take two arguments. class DFD { ... getEndDatetime(): string; getEndDatetime(startTime?: ...

Typescript error message TS2314: One type argument is required for the generic type 'Array<T>'

I recently started my journey in learning typescript and have written some basic code. class Learning { subjects: Array[string]; hoursPerDay: number; constructor(subj: Array[string], hrs: number) { this.subjects = subj; thi ...

Can you explain the purpose and functionality of the following code in Typescript: `export type Replace<T, R> = Omit<T, keyof R> & R;`

Despite my efforts, I am still struggling to grasp the concept of the Replace type. I have thoroughly reviewed the typescript documentation and gained some insight into what is happening in that line, but it remains elusive to me. ...

How can esbuild be used to load .wglsl files in Typescript files?

I'm currently utilizing esbuild to bundle my Typescript code, but I'm facing a challenge with configuring a loader for ".wgsl" files. Here is my app.ts file: import shader from './shader.wgsl'; //webgpu logic This is my shader.d.ts fi ...

Oops! There seems to be an issue with locating a differ that supports the object '[object Object]' of type 'object', like an Array

I'm currently encountering an error that reads: (ERROR Error: NG02200: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables, such as Arrays. Did you mean to use the key ...

Angular: Converting JSON responses from HttpClient requests into class instances

I am facing an issue with the following code: public fetchResults(searchTerm: string): Observable<Array<SearchResult>> { let params = new HttpParams().set('searchTerm', searchTerm); return this.http .get<Array< ...

Learn the steps to switching a route in an Angular 11 application from one existing application to another

Imagine I have two separate application folders; Application A and Application B. Application B utilizes login, logout, and a few other session storage values from Application A. My goal is to redirect or replace the route from Application A to Application ...