Encountering a problem: Unable to locate a supporting object '[object Object]' of type 'object' when attempting to populate a list of objects

Struggling to populate the options with server data, I tried simplifying the logic yet encountered the same error.

Here's the HTML snippet for the options:

<div class="col-md-4">
<mat-form-field class="example-full-width" *ngIf="!isAdmin; else userList">
    <input matInput placeholder="Owner" type="text" [(ngModel)]="device.owner" name="owner" [disabled]="true">
</mat-form-field>
<ng-template #userList>
    <div class="col-md-12" *ngIf="isUserListFilled()">
        <mat-form-field>
            <mat-select placeholder="List of users">
                <mat-option *ngFor="let usr of userList" [value]="usr._id">
                    {{usr.name}}
                </mat-option>
            </mat-select>
        </mat-form-field>
    </div>
</ng-template>

And here's the code used to populate the template:

  export class DeviceSettingsComponent implements OnInit {
  userList: any[] = [];

  isAdmin = true;

  constructor(private backendService: BackendService, private route: ActivatedRoute) { }

  ngOnInit() {
this.userList = [{_id: "test1", name: "test name"}];
this.device = new DeviceSettings();
this.sub = this.route.params.subscribe(params => {
  this.deviceId = +params['id']; // (+) converts string 'id' to a number
});
if(this.deviceId){
  console.log(`Retrieving info for device with ID ${this.deviceId}`);
}


if (this.isAdmin) {
  this.backendService.getUsers().subscribe(
      (response) => {
        if (response.users) {
          let usersMapped = response.users.map(item => {
            return {_id: item._id, name: item.email};
          });
          //this.userList = usersMapped;
          console.log(this.userList);
        }
      },
      (error) => console.log(error)
  )
}
}
    isUserListFilled(){
        if(!this.userList) return false;
        if(this.userList.length === 0) return false;
        return true;
      }

      onOwnerChanged(event){
      console.log(event);
  }

Despite simplifying the code and attempting to populate the items with options, I encountered the following error:

ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. 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] (DeviceSettingsComponent.html:33) at Object.debugUpdateDirectives [as updateDirectives] (core.js:20432) at checkAndUpdateView (core.js:19828) at callViewAction (core.js:20069)

If anyone knows what might be causing this error, please share insights. Similar methods worked fine in other components, so unsure where potential issues may lie.

Answer №1

There seems to be a conflict between your userList and the #variable, template name.

#userList //template name

To resolve this issue, you need to clearly differentiate between the two entities.

<ng-template #userList>//template name is useList
    <div class="col-md-12" >
        <mat-form-field>
            <mat-select placeholder="List of users">
                <mat-option *ngFor="let usr of userList" [value]="usr.id">//userlist as 
an array
                    {{usr.name}}
                </mat-option>
            </mat-select>
        </mat-form-field>
    </div>
</ng-template>

Check out the demo

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

Contrast between sourcing a file from the current directory versus from the node_modules folder

Why does the typescript compiler accept importing from a JS file in the local directory but raises an error when importing from node_modules? Code: import { t2 } from "./t1.js" t2.hello(); import { mat4 } from "./node_modules/gl-matrix/esm ...

Bidirectional binding with complex objects

In my Angular2 app, I have a class called MyClass with the following structure: export class MyClass { name: Object; } The name object is used to load the current language dynamically. Currently, for two-way binding, I am initializing it like this: it ...

Optimal approach for designing interfaces

I have a situation where I have an object retrieved from the database, which includes assignee and author ID properties that refer to user objects. As I transform a number into a user object, I am unsure about the best practice for defining the type of the ...

Problem with custom anchor component in React that needs to perform an action before being clicked

React Component (Custom Anchor) import React from 'react'; class Anchor extends React.Component { onClick = (event) => { // ----------------------------- // send Google Analytics request ...

Does the message "The reference 'gridOptions' denotes a private component member in Angular" signify that I may not be adhering to recommended coding standards?

Utilizing ag-grid as a framework for grid development is my current approach. I have gone through a straightforward tutorial and here is the code I have so far: typography.component.html https://i.stack.imgur.com/XKjfY.png typography.component.ts i ...

Creating TypeScript Classes - Defining a Collection of Objects as a Class Property

I'm trying to figure out the best approach for declaring an array of objects as a property in TypeScript when defining a class. I need this for a form that will contain an unspecified number of checkboxes in an Angular Template-Driven form. Should I ...

Unable to bring in Angular2 bootstrap function

I am currently setting up a basic Angular 2 (beta 2) app using TypeScript. I have the code for app.ts file taken from Angular's most recent setup guide import {Component, View, bootstrap} from 'angular2/angular2'; @Component({ selector: ...

Request with missing authentication header in Swagger OpenAPI 3.0

When generating the swagger.json using tsoa for TypeScript, I encountered an issue. Even after adding an access token to the authorize menu in Swagger and making a request to one of my endpoints, the x-access-token header is missing from the request. What ...

Is it possible to refresh the component view using the service?

I am interested in developing a NotificationService that will be utilized to showcase a notification from another section. My inquiry is, how can I refresh the view of a component using a service? My ultimate goal is to have the capability to embed a comp ...

Tips for delivering a variable to a React Native Stylesheet

Is there a way to pass a variable to the "shadowColor" property in my stylesheet from an array declared in the code above? I keep encountering a "Can't find name" error. Attempting to use a template literal has not resolved the issue. Any assistance w ...

Shifting focus among an array of standard <input> controls with each keystroke

When working with Angular, I encountered a situation where I have an array of arrays of numbers, as shown below: [ [1,1,1,1], [1,1,1,1] ] In my HTML file, I am using ngFor to generate input controls like this: <table> <tbody> ...

Having trouble updating npm using npm install npm@latest -g and encountering an error?

Encountering errors and warnings while updating npm to the latest version c:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\Web Tools\External>npm cache clean --force npm WARN u ...

What is the best approach for managing errors between Node.js and Angular 2?

I have a simple task at hand. Let's consider a scenario where a user can submit news through a form that has two fields: title and content. The title field is required, which can be validated both on the client side and server side using the following ...

The Vue route parameters are not recognized within the function type

Seeking assistance on extracting parameters from my route in a vue page, I have the following implementation: <script lang="ts"> import { defineComponent } from 'vue'; import { useRoute } from 'vue-router'; export ...

Displaying an array assigned within an Angular class

I'm facing an issue displaying a list of content using an array in Angular. Despite the app functioning properly, no data seems to be returned. Other apps are loading fine. Although the service has been added to the app.module.ts file, there are no e ...

Modifying data types within complex nested object structures

I am looking to traverse the data structure recursively and create a custom type with specific fields changed to a different type based on a condition. Using the example structure below, I aim to generate a type (Result) where all instances of A are repla ...

What is the best method for launching a Node.js (Express) app on a live server automatically?

My Angular app relies on an express backend. What is the best way to deploy this application on a remote server so that it always runs smoothly? ...

The property you are trying to access is not defined on the enum type in Types

Looking to revise the TypeScript syntax of a lesson found at this link. I am aiming to extract a specific type from a union type using the following syntax: Actions['type'][ActionTypes.FEED_CREATE_POST] The available action types are defined a ...

Display permanent components in Angular while nesting components

Currently, I am incorporating the admin module within the main app module in my project Within the admin module, there are 2 components - register and login. Additionally, the admin module has its own routing module. Now, my task is to create a navbar sp ...

Validate an object to check for null or empty fields, including arrays, using Javascript

Currently, I am facing an issue with iterating through a complex array that contains objects and embedded arrays. The goal is to detect any empty or null values within the array. However, my challenge lies in accurately determining if an array is empty. De ...