Guidelines for utilizing NgFor with Observable and Async Pipe to create Child Component once the data has been loaded

Encountering an issue while attempting to display a child component using data from an Observable in its parent, and then utilizing the async pipe to transform the data into a list of objects for rendering with *NgFor. Here's what I've done:

  1. Create Observable Data in Parent Component:

    // Parent Component
    dataSet$!: Observable<Data[]>;
    
    ngOnInit() {
      this.dataSet$ = this.serviceData.getData();
    }
    
  2. Pass Data from Parent to Child Using Async Pipe:

    <!-- Parent Component Template -->
    <ng-container *ngIf="dataSet$ | async as dataSet">
      <app-row-data-list *ngFor="let data of dataSet" [data]="data"></app-row-data-list>
    </ng-container>
    
  3. Child Component with @Input Property:

    // Child Component
    export class RowDataListComponent {
      @Input() data!: Data;
    }
    

Despite my efforts, the data is not displaying as expected, and the child components are not appearing.


I have tried implementing the solutions provided in the following responses:

However, none of these solutions resolved the issue. I have also conducted extensive research on this matter.

I have spent several hours trying to resolve this problem, so any assistance would be greatly appreciated.

Thank you.

Edit: Following guidance from one of the answers here, I was able to address the issue. I followed these steps (Refer to Stack Blitz example):

https://angular-ch...示例-uxz7dg.stackblitz.io

Answer №1

I cannot guarantee the specific code you are looking for, but here is a functional example:

interface Article {
  articleId: number;
  userId: number;
  title: string;
  published: boolean;
}

type Articles = Article[];

@Injectable({ providedIn: 'root' })
class ArticleService {
  private http = inject(HttpClient);

  getArticles() {
    return this.http.get<Articles>(`https://jsonplaceholder.typicode.com/posts`);
  }
}

@Component({
  selector: 'app-article',
  standalone: true,
  template: `
    <pre>{{article() | json}}</pre>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [JsonPipe],
})
export class ArticleComponent {
  article = input<Article>();
}

@Component({
  selector: 'app-root',
  standalone: true,
  template: `
    <h1>Greetings from {{ user }}!</h1>
    <app-article *ngFor="let post of (posts$ | async)" [article]="post"></app-article>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [ArticleComponent, NgFor, AsyncPipe],
})
export class App {
  user = 'Angular';

  private articleService = inject(ArticleService);

  posts$ = this.articleService.getArticles().pipe(startWith([]), share());
}

bootstrapApplication(App, { providers: [provideHttpClient()] });

Take a look at this StackBlitz sample

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

Navigate to a concealed area once the information has been loaded in Angular

I'm working on my very first Angular app, which is a basic weather application. I've encountered an issue where I want to scroll to a specific section after the data has been loaded from the API. This particular section is initially hidden until ...

A step-by-step guide on assigning values to an Angular Material Auto Complete component in Angular 7

Hey there! I'm currently using the Angular Material Auto complete component in my Angular 7 app and I'm trying to find a way to bind a value from an API response to it. Can someone help me out with a solution for this? HTML: <mat-form-field> ...

When trying to pass props into setup using VueJS 3 Composition API and TypeScript, an error may occur stating: "Property 'user' does not exist on type"

I need help figuring out why TypeScript is not recognizing that props.user is of type UserInterface. Any advice or guidance would be greatly appreciated. You can reach me at [email protected], [email protected], [email protected]. This seem ...

Navigating through multiple pages in Angular2 with Rails5

Typically, in Rails development, I would use will_paginate and be done with it. However, my current project involves using Rails5 solely as an API, while the front-end is entirely Angular2. I've explored NG Bootstrap4's Pagination, but I'm ...

Svelte with Typescript: Uncovering the Types of Props

Issue: I am trying to create a function that can take a component as the first argument and its props as the second argument in a generic manner import Modal from "./Modal.svelte"; function openModal(component: typeof Modal, componentProps: ...

The type 'Dispatch<any>' cannot be assigned to the type '() => null'. Error code: ts(2322)

While working on my application context, I encountered a typescript error: 'Type 'Dispatch' is not assignable to type '() => null'.ts(2322)'. I am fairly new to typescript and struggling to understand this error. Below is ...

Handling JSON data with Reactive Extensions in JavaScript

Hey everyone, I'm a beginner in Angular and RxJS coming from a background in VueJS. I've been struggling to grasp the inner workings of RxJS and would really benefit from some guidance from more experienced individuals regarding my current issue. ...

Leveraging import and export functionality in TypeScript while utilizing RequireJS as a dependency

I am in the process of transitioning a complex JavaScript application from Backbone/Marionette to TypeScript. While making this shift, I want to explore the benefits of exporting and importing classes using files as modules. Is it necessary to incorporat ...

Steps to resolve the issue with "Error: StaticInjectorError(AppModule)[NgbDropdown -> ChangeDetectorRef]"

My attempt at creating a web app using Angular resulted in successful compilation with no errors. However, upon execution, the browser displays a blank page accompanied by the following error message: ERROR Error: Uncaught(in promise): Error: St ...

Encountered an issue during the transition from Angular 7 to Angular 9

After following the advice in the second response of this discussion, I successfully upgraded to Angular 9. However, I am now encountering an issue in the browser console when running my project. Package.json "dependencies": { "@angular-devkit/build- ...

Encountering TypeScript errors while trying to implement Headless UI documentation

import { forwardRef } from 'react' import Link from 'next/link' import { Menu } from '@headlessui/react' const MyLink = forwardRef((props, ref) => { let { href, children, ...rest } = props return ( <Link href={href}&g ...

How can you test component methods in Angular?

As a beginner in Angular, I am currently learning how to write tests and struggling with mocking and testing methods from components. The structure of my HTML is as follows: There is a table displaying all certificates. By clicking the "edit" button, you ...

Declaring a function type with a void parameter type in typescript

Embarking on my journey with ts and currently exploring TypeGraphQL. I came across something that caught my attention and seems unfamiliar to me: export declare type ReturnTypeFunc = (returns?: void) => ReturnTypeFuncValue; How should this type be unde ...

Both radio buttons are being chosen simultaneously

<div class="container"> <div class="row"> <form> <div class="form-group"> <label>username</label> <br /> <input type="text" class=" ...

Utilizing Filters (Pipes) in Angular 2 Components without Involving the DOM Filters

When working in Angular 1, we have the ability to use filters in both the DOM and Typescript/Javascript. However, when using Angular 2, we utilize pipes for similar functionality, but these pipes can only be accessed within the DOM. Is there a different ap ...

TypeScript async function that returns a Promise using jQuery

Currently, I am facing a challenge in building an MVC controller in TypeScript as I am struggling to make my async method return a deferred promise. Here is the signature of my function: static async GetMatches(input: string, loc?: LatLng):JQueryPromise& ...

Encountered a runtime error while processing 400 requests

Current Situation: When authenticating the username and password in my Ionic 2 project using WebApi 2 token authentication, a token is returned if the credentials are correct. However, a 400 bad request error is returned if the credentials are incorrect. ...

Angular auto-suggest components in material design

Can someone assist me in resolving my issue? I am trying to incorporate an autocomplete feature with a filter into my form. .ts file : contactArray; selectedContact: IContact; myControl = new FormControl(); filteredContact: Observable<string[] ...

Sharing Information Across Angular Routes

I've been encountering a slight issue when working with routes in Angular 4. Whenever I attempt to pass data from one component to another using navigate('root', data), all I end up receiving is [object Object],[object Object],[object Object ...

Customize the border color of a dynamic textbox with Angular

I'm using Angular to create dynamic textboxes. <span *ngFor="let list of lists[0].question; let i = index"> {{ list }} <input type="text" *ngIf="i != lists[0].question.length-1" [(ngModel)] ...