`What is the best way to transfer an observable to a child component?`

I am facing an issue with passing an Observable down to a child component. I have tried various solutions but none seem to work.

parent.component.ts:

export class ParentComponent {
  items$ = of([{name: "Item 1"}, {name: "Item 2"}]);
}

parent.component.html:

<child-component [items$]="items$"></child-component>

child.component.ts:

export class ChildComponent {
  @Input() items$?: Observable<Item[]>;
}

child.component.html:

<ul>
  <li *ngFor="let item of items$ | async">{{ item.name }}</li>
</ul>

Upon logging items$ in the ChildComponent's ngOnInit(), it shows as undefined. It is important for me to use dynamic streams rather than hardcoded services in order to maintain flexibility. Any suggestions on how to resolve this?

Edit: Apologies for the confusion caused by my mistake. The example provided was simplified for clarity, however, the issue I faced was due to a misplaced closing tag in the HTML code:

<my-component
  [field1]="someVar1"
  [field2]="anotherVar2">
  [items$]="items$">
</my-component>

In spite of no errors being flagged in VSCode and the layout appearing correct, the extra > after [field2]="anotherVar2" caused the problem.

Answer №1

Dealing with observable inputs can sometimes be challenging, but you can simplify the process by utilizing the async pipe to extract the value of the item as demonstrated in this example:

  @Component({
  selector: 'child',
  standalone: true,
  imports: [CommonModule],
  template: `
  <h1>child</h1>
  {{data}}
  <hr/>
  `,
})

export class Child {
  name = 'Angular';
  @Input() data: number;
}

@Component({
  selector: 'my-app',
  standalone: true,
  imports: [CommonModule, Child],
  template: `
  <child [data]="parent$| async"></child>
  `,
})
export class Parent {
  parent$ = interval(500);
}
bootstrapApplication(Parent);

You can explore the complete example by visiting:

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

I'm puzzled as to why I am unable to invoke a class method within this callback function. The error message indicates a TypeError: 'this' is undefined

Currently, I am troubleshooting a challenge in my Angular application that involve TypeScript. The issue lies within a method in a TypeScript class: findArtistBidsAppliedByCurrentWall(bid):Observable<Bid[]> { console.log("findArtistBidsApplied ...

Prevent selection based on function in Angular

I'm attempting to prevent certain options from being selected based on a specific method. For instance, let's say I have four options: A B C D In my method (let's use "x" as an example): if(name == A) { disable the selection for option A. ...

Creating a dynamic table with columns of fixed width in Angular on the fly

I am struggling to create a data table with fixed column widths (20% each). I have incorporated div elements in my table structure to enable dynamic row creation using Angular, but this has caused some design issues. My goal is for all rows to occupy 100% ...

Utilize the fetch function within a React functional component

I have been experimenting with different methods to fetch data only once before rendering, but I am encountering some challenges: It is not possible to call dispatch in componentDidMount as there is a restriction that it can only be done in Functional c ...

Encountering a Npm ERR! when deploying Angular 6 to Heroku due to missing Start script

I am experiencing an issue with my simple angular 6 app after deploying it to Heroku. When I check the logs using the command heroku logs, I encounter the following error: 2018-07-15T00:45:51.000000+00:00 app[api]: Build succeeded 2018-07-15T00:45:53.9012 ...

Unraveling NGRX: a guide to invoking factory selectors from within additional selectors

NGRX has deprecated selectors with props in version 11. The recommended method now is to create factory selectors. How can you nest selectors or call one from another and pass the state between them? Prior to the change, if we had the following two selec ...

Issue encountered while connecting ipcRenderer with ipcMain in an electron application

I recently set up Angular CLI in Electron, and I have a link that triggers a function which communicates between ipcRenderer and ipcMain: Here is the HTML code: <a (click)="check()"> click </a> This is the component code: constructor(privat ...

Is there a way to access the final child element within a mat-accordion component using Material-UI and Angular 8?

I have a mat-accordion element with multiple expansion panels that are generated dynamically. How can I programmatically select and expand the last mat-expansion-panel element? <mat-accordion> <mat-expansion-panel> text 0 </mat-ex ...

Tips on eliminating expansion upon button click in header within an Angular application

While utilizing Angular Materials, I encountered a challenge with the mat-expansion component. Every time I click on the buttons within the expansion panel, it closes due to the default behavior of mat-panel. Requirement - The panel should remain expanded ...

Is it possible to dynamically change an ngModel value directly from the component?

I'm currently immersed in an Angular project and my initial file setup was like this: dog.ts: export interface Dog { name: string; age: number; breed: string; } dog.component.ts: import { Dog } from '../dog'; @Component({ //setup ...

Angular 2: Triggering the "open" event for a Bootstrap dropdown

I am currently in the process of developing a directive that will trigger a Bootstrap dropdown to open when clicked and close it when the mouse leaves. Below is the code for the dropdown directive: import {Directive, HostBinding, HostListener} from ' ...

Discover the power of debugging Typescript in Visual Studio Code with Gulp integration

I've been working on setting up an express/typescript/gulp application, and while it's functional, I'm struggling to debug it using source-maps. Here is how I've set it up: Gulp File var gulp = require('gulp'), nodemon ...

Exploring the versatility of Angular by creating various flex layouts with Angular Material cards

I'm struggling to implement the design shown below using cards and a flex layout in a responsive way. I've tried working on it using StackBlitz but haven't been able to get it right - the margin and layout get messed up on different screens. ...

What is the best method for extracting individual JSON objects from a response object and presenting them in a table using Angular?

After receiving a JSON Array as a response Object from my Java application, I aim to extract each object and display it on the corresponding HTML page using TypeScript in Angular. list-user.component.ts import { HttpClient } from '@angular/common/h ...

Having trouble with @HostListener on iPad or iOS devices? I'm currently using a Bluetooth keyboard to navigate and interact with an Angular app

I am currently creating a web application using Angular 6 for an iPad with a screen size of 9.7 inches. I have implemented code similar to the one found at this link. import { Component, HostListener } from '@angular/core'; export enum KEY_CODE ...

Having trouble with my Angular 4 application when trying to make a POST request to a

I am struggling to create a straightforward login verification process using Angular 4, PHP, and MySQL. Currently, I can successfully send the user details to PHP but I am unable to retrieve the status afterward, and I'm not sure why. Basically, I ne ...

Is your Angular app missing i18next translations?

Can Angular's i18next provider be configured to hide any value when the key is not defined? The issue arises when there is no translation defined for a specific key like my:key. I want to display an empty string in the template instead of showing the ...

Retrieve the Typescript data type as a variable

I have the following components: type TestComponentProps = { title: string; } const TestComponent: React.FC<TestComponentProps> = ({ title, }) => { return <div>TestComponent: {title}</div>; }; type TestComponent2Props = { bod ...

Angular app encountering an error with inline style due to server's CSP response header configuration

I have encountered a problem while working on my Angular application. Specifically, I am currently developing in an Angular 8 environment using the CLI. When running the application on my local server, everything functions as expected without any issues. ...

What should be the return type of a Jest test when written in a Typescript function?

When encapsulating a Jest test in a function with TypeScript, what is the expected return type? Thank you. const bar:ExpectedReturnType = () => test('this is another test', expect(false).toBeFalsy()); ...