Guide to incorporating external JSON data into a Select dropdown in Angular 7

Issue : How to populate JSON values retrieved from a REST API into a Select statement?

team.component.html

<mat-select placeholder="Select Name" [(ngModel)]="name">
  <mat-option *ngFor="let currentName of nameValuesArray" [value]='currentName.name'>
    {{currentName.name}}
  </mat-option>
</mat-select>

team.component.ts

export class UpdateTeamRosterComponent implements OnInit {

  nameValuesArray;
  name;

  constructor(private fetchData : FetchdataService) { }

  ngOnInit() {
    console.log('ngOnIt called');
    this.nameValuesArray = this.fetchData.getAllEmployeeNames('DCP').subscribe(data=>{
      this.nameValuesArray = JSON.stringify(data);
    });

  }
}

ERROR

  UpdateTeamRosterComponent.html:1 ERROR Error: Cannot find a differ supporting object '[{"name":"Ajith"},{"name":"Anand"},{"name":"Bharath"}]' of type 'string'. NgFor only supports binding to Iterables such as Arrays.
      at NgForOf.push../node_modules/@angular/common/fesm5/common.js.NgForOf.ngDoCheck (common.js:3161)
      at checkAndUpdateDirectiveInline (core.js:18623)
      at checkAndUpdateNodeInline (core.js:19884)
      at checkAndUpdateNode (core.js:19846)
      at debugCheckAndUpdateNode (core.js:20480)
      at debugCheckDirectivesFn (core.js:20440)
      at Object.eval [as updateDirectives] (UpdateTeamRosterComponent.html:2)
      at Object.debugUpdateDirectives [as updateDirectives] (core.js:20432)
      at checkAndUpdateView (core.js:19828)
      at callViewAction (core.js:20069)

Data is fetching correctly from the server The issue lies in rendering the data onto the select statement

Answer №1

Set the observable to the designated field.

this.employeeList = this.dataService.getAllEmployees('NYC');

Next, implement the async pipe within the template:

<mat-option *ngFor="let employee of employeeList | async" [value]='employee.name'>

Answer №2

Avoid using JSON.stringify as it will convert your array into a string. Instead, modify it in the following way:

this.nameValuesArray = data;

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

a distinctive identifier for the id attribute in Angular when using a radio button

I am struggling to set a unique id for each radio button within the same form. The button is repeated 4 times and I need a distinct id for each instance. In this case, field 1 should have the first two radio choices and field 2 should have the next 2 radi ...

The ngx-material-timepicker lacks proper design when the minutesGap is set to 1

https://i.sstatic.net/J4z5H.png Check out this example of HTML code I have written: <mat-form-field> <mat-label>StartTime</mat-label> <input matInput readonly [ngxTimepicker]="timeStart" [formControlName]="'sta ...

What is the process for invoking a service from a component?

I'm currently facing an issue with my service that is responsible for making HTTP requests and returning responses. The problem arises when I try to display parts of the response on the screen within my component, as nothing seems to be showing up des ...

Using Datatable.net with Angular 6 for Change Monitoring

I've been encountering several issues with the custom datatable component that I created. One specific problem is that when I delete a row from my datatable, not only does the row disappear, but also the pagination functionality and other features st ...

Issues with loading SourceMap in DevTools after upgrading from Bootstrap 3 to 4

I am currently working on a project with Angular 6 and .NET MVC where I am in the process of upgrading from Bootstrap 3 to Bootstrap 4. Initially, I had been using the Bootstrap 3 CDN and everything was working smoothly. However, I recently had to switch t ...

The functionality of the Vert.x event bus client is limited in Angular 7 when not used within a constructor

I have been attempting to integrate the vertx-eventbus-client.js 3.8.3 into my Angular web project with some success. Initially, the following code worked perfectly: declare const EventBus: any; @Injectable({ providedIn: 'root' }) export cl ...

Guide to accessing private property in TypeScript using the prefix # syntax

Is there a way to access private properties of a class in TypeScript that are denoted by the prefix # symbol? I need this for unit testing purposes. class A { #pr: number; pu: number constructor(pr: number, pu: number) { this.#pr = pr; ...

The function ValueChange remains uninvoked

Query: The issue is that valueChanges is only triggered for the entire form and not for specific controllers. Although this approach works, it returns the complete object. public ngOnInit(): void { this.form.createWagonBodyForm(); ...

Mastering the proper implementation of observables, async/await, and subscribing in Angular

I have a JSON file located at assets/constants/props.json. Inside this file, there is a key called someValue with the value of abc. The structure of the JSON file can be seen in the following image: https://i.stack.imgur.com/MBOP4.jpg I also have a serv ...

Circular dependency in Angular occurs when there is a loop in the way dependencies are injected

I am facing an issue with injecting dependencies into the interceptor. Specifically, I am trying to inject TranslateService into HttpErrorInterceptor, but encountering a cyclic dependency error. Interestingly, when I remove the TranslateService injection, ...

Each time new scripts are loaded, the Angular 13 window.ng.ɵcompilerFacade gets swapped out for a fresh

New Update: After observing the behavior of loading components/modules in my application, I have noticed a conflict arising between window.ng.ɵcompilerFacade and v13 compliance format when switching between Angular versions. The issue occurs when loading ...

Applying a setvalidator to a FormControl doesn't automatically mark the form as invalid

HTML code <div> <label for="" >No additional information flag:</label> <rca-checkbox formControlName="noAdditionalInfoCheckbox" (checkboxChecked)="onCheckboxChecked($event)"></rca-chec ...

How to upload files using 3 input fields in Angular?

Seeking assistance on uploading 3 files using 3 different inputs. I'm a beginner in Angular, so please excuse any naive inquiries. Here is the code snippet: BookFormComponent.ts: export class BookFormComponent implements OnInit { audioFile: File ...

Can TypeScript be configured to recognize the generic object assignment illustrated below?

Take a look at this code snippet: type Type = 'one' | 'two' | 'three' type TypeSelection = 'one' | 'two' interface InnerObject<T extends Type> { name: string, type: T } type Obj<K extends Ty ...

Angular 6: Transform object and add to array

My service includes a method called getCategory() that retrieves categories from the server. The method looks like this: getCategory(): Observable<CategoryModel[]> { return this.http.get<CategoryModel[]> (this.productUrl) .pipe( ...

Even though the model value is set to true, the material check box remains unchecked

My mat-table contains data and checkboxes. The checkboxes should only be checked when the element.select property is true. However, when I use [(ngModel)]="element.select", all the checkboxes end up getting checked. Below you can find the code snippet: &l ...

Express: Every declaration of 'user' must have the same modifiers

In my application, I am utilizing both express and passport. Within these packages, there is a user attribute within the Request interface. Currently, the express package has a user attribute in the request object, such as req.user, but no additional prope ...

Utilizing multiple modules with a shared component leads to errors in Angular 2

There is a shared component called GoComponent that I need to utilize in two different modules: FindPageModule and AddPageModule. Unfortunately, when I include it in the declarations of both "FindPageModule" and "AddPageModule," I encounter an error: f ...

What is the best way to pass data between sibling components using services?

I'm looking to connect a service to a component that can fetch data, share objects, and communicate with other components that are already linked to the database. I've established a service named DashService as follows: import { Injectable } fro ...

Which Angular component, directive, or pipe would be best suited for creating dynamic HTML content similar to this?

(I am transitioning from React to Angular, so please bear with me if my question has a hint of React influence.) I am in need of developing an Angular component that can accept a string along with a list of terms within that string for displaying tooltips ...