Looping through Observable with an Array using *ngFor in Angular

My Angular App is having trouble displaying all the items of a device due to issues with iterating through an observable array. The error message I am currently encountering is as follows:

Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

<tbody *ngFor="let item of (device | async).itemMap">
  <tr>
    <td>{{ item.name }}</td>
    // ...
  </tr>
</tbody>
export interface Device {
  items: DeviceItem[];
}

@Input()
public device: Observable<Device>;

Answer №1

If your observable is emitting a single Device model, not an array of Device:

export interface Device {
  items: DeviceItem[];
}

public device$: Observable<Device>;

In the provided code snippet, it is advisable to follow the convention of using a $ symbol as a suffix for observables like device$.

Your template code should be:

  <tr *ngFor="let item of (device$ | async).items">
    <td>{{ item.name }}</td>
    // ...
  </tr>

Alternatively,

  <ng-container *ngIf="device$ | async as device">
    <table>
      <tr *ngFor="let item of device.items">
        <td>{{ item.name }}</td>
        ...
      </tr>
    </table>
  </ng-container>

Answer №2

When using *ngFor, it will iterate only over a collection. To make this work, you need to create a subject that contains your device type array and fill the data into it.

public devices: Subject<Device[]> = new Subject();

You can then populate this 'devices' subject with data like so -

this.devices.next(data);

Answer №3

Assign the mapping of the device to items in the TypeScript file (manual updates required if input changes):

export interface Device {
  items: DeviceItem[];
}

@Input()
public device: Observable<Device>;
public items$ = device.pipe(map(x => x.items));

Then proceed to use it as you normally would:

<tr *ngFor="let item of items$">
<td>{{ item.name }}</td>
// ...

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

Incorrectly aligned highlighted labels are appearing on the Kendo chart category axis item labels

My current project involves using the kendo chart to generate charts, and I need specific labels to show up as bold text. To achieve this, I am utilizing the visual method which allows me to customize labels and render them with createVisual(). However, w ...

Managing Observable<Person[]> in ng-bootstrap typeahead instead of Observable<string[]>: a complete guide

I'm new to Angular/Typescript and have a question. I recently tried out the example from Wikipedia in ng-bootstrap typeahead. Instead of using the Wikipedia call, I decided to use a custom REST service that has the following GET endpoint: GET /pers ...

Unsure about the commit hash referenced in the tsd.json file

Explore the history of angular-ui-router d.ts file using the commit hash Within my tsd.json file, I have the following details: { "version": "v4", "repo": "borisyankov/DefinitelyTyped", "ref": "master", "path": "typings", "bundle": "typings/tsd ...

Weighing the importance of a multiple-choice quiz

I am faced with the challenge of assessing 25 multiple choice questions, each offering 4 answer choices worth varying points. Additionally, I have 2 free response questions that I wish to score based on the time taken to answer them. My proposed scoring ru ...

Currently in motion post file selection

I am currently facing an issue with a button that triggers a file selector pop-up. Below is the code snippet: <button mat-raised-button (click)="inputFile.click()">Choose a file</button> <input #inputFile type="file" [style.display]="' ...

When a URL is entered, information is not retrieved from the database

I have a simple app setup where the data (iPhones from the database) is fetched in the AppComponent itself. ngOnInit(): void { this.iphoneservice.fetchIphones(); } The fetchIphones method is located in my iPhoneService file and consists of 3 functio ...

Having trouble monitoring button clicks with Jest and React Testing Library while testing a component scenario

Hey there, I'm new to React testing library and I've been struggling with writing a test case that isn't giving me the results I expected. I could really use some guidance. When I run npm run test, it shows the expected number of calls >= ...

Utilizing combinedReducers will not prompt a re-render when dispatching actions

When I refrain from using combineReducers: const store = createStore<StoreState,any,any,any>(pointReducer, { points: 1, languageName: 'Points', }); function tick() { store.dispatch(gameTick()); requestAnimationFrame(tick) ...

Having trouble accessing multiple items in JSON format using AsyncStorage in React Native

After attempting to retrieve all items stored in my AsyncStorage, I encountered an issue where the response was not in JSON format. Instead, it was returned in a different format: [["engineyard", "{\"login\":\" ...

Typescript compiler still processing lib files despite setting 'skipLibCheck' to true

Currently, I am working on a project that involves a monorepo with two workspaces (api and frontEnd). Recently, there was an upgrade from Node V10 to V16, and the migration process is almost complete. While I am able to run it locally, I am facing issues w ...

Library for injecting dependencies - changing the names of injected variables

Is there a way to inject lodash by a different name using ES6/ES7/ES8 or TypeScript? let val = function(lodash){ // lodash will be injected, simply by using require('lodash'); }; What if I want to rename the import? Can I do something like t ...

What is the best way to remove all selected items in a dropdown menu?

My issue pertains to Angular and Typescript. I am facing a challenging problem with a dropdown menu that has 3 items. The unique aspect is that I am not utilizing the standard select HTML tag; instead, I am using my company's custom toolkit, which ser ...

What is the best way to apply a basic filter to an ion-list in an Ionic 4 application?

Currently, I am working with a list that is cycling through the keys of an SQlite database by utilizing Ionic storage. With the help of Angular slice, I have successfully excluded the first two rows from the list. However, I am now faced with the challenge ...

Incorporate the latest value into an array of objects using JavaScript, taking into account its frequency

Hey there, I have an array of objects where I need to add a new property or value to each object based on its order number occurrence. For example, in the array of objects, there is a property called order number. If an object contains the highest order n ...

Issue with Bot framework (v4) where prompting choice in carousel using HeroCards does not progress to the next step

Implementing HeroCards along with a prompt choice in a carousel is my current challenge. The user should be able to select options displayed as HeroCards, and upon clicking the button on a card, it should move to the next waterfall function. In the bot fr ...

The component fails to load on the designated router outlet

I have updated my question to provide more clarity. I am working with 2 routing files, admin-layout.routing.ts and parameter.routing.ts. In admin-layout.routing.ts, there is a path for property.component.ts with a child called parameter.component.ts. Insid ...

What is the rationale behind Typescript permitting the assignment of an "any" object type to a class object?

Within my codebase, there is a class object that I have initialized: groupNameData: GroupNameData = new GroupNameData(); In addition, I also have an any object called groupNameDatas. groupNameDatas: any; Experiment 1 (class = any) To experiment with ...

Storing data locally in Angular applications within the client-side environment

As I delve into Angular and TypeScript, I've encountered a perplexing issue. Let's say I have two classes - Employee and Department. On the server-side, I've established a Many-To-One relationship between these entities using Sequelize: db. ...

What is the best way to develop a function that can take in either a promise or a value and output the same type as the input parameter?

I'm currently working on a TypeScript function that can handle either an A type or a Promise<A>. In this case, A represents a specific concrete type, and the function should return the same type. If it receives a Promise<A>, then the retur ...

Tips for retaining scroll position in Angular 2

Suppose I am currently on page 1. I scroll halfway through the page and then click a link that takes me to page 2 using the Angular router. When I use the "back" button, I want page 1 to be scrolled halfway down, just like it was before I left the page. H ...