`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

Exploring the world of nested observables in Angular through cascading HTTP requests

My plan involves the following steps: Make a request to https://reqres.in/api/users/2 This request will return the following response. { "data": { "id": 2, "first_name": "Janet", "last_name": "Weaver", "avatar": "https://s3.ama ...

When working with TypeScript, how do you determine the appropriate usage between "let" and "const"?

For TypeScript, under what circumstances would you choose to use "let" versus "const"? ...

The value from select2 dropdown does not get populated in my article in Angular

I am attempting to link the selected value in a dropdown menu to an article, with a property that matches the type of the dropdown's data source. However, despite logging my article object, the property intended to hold the selected dropdown value app ...

Implementing experimental decorators and type reconciliation in TypeScript - A step-by-step guide

My basic component includes the following code snippet: import * as React from 'react'; import { withRouter, RouteComponentProps } from 'react-router-dom'; export interface Props { }; @withRouter export default class Movies extends R ...

Retrieve JSON Data in Angular 2

I've defined a model with the following structure: export class ExampleData{ id: string; url: string; } When I make a call to a service, it returns the JSON data shown below: [ { "id": "abc", "url": "/path/to/folder" }, { ...

Automatically compile files while performing an npm install or update

I am looking for a way to automatically compile my TypeScript code into JavaScript when another project requires it. For example, when a project runs npm install or updates with my project as a dependency, I want a specific command to be executed after all ...

There was an issue with the layout detection in Angular. The app-layout selector could not find a matching element in the code

Currently diving into the world of Angular and embarking on my first project, I've hit a roadblock. After initiating a terminal with the server, all I get is a blank page when I load my browser. Upon inspecting the page using f12, an error message pop ...

Executing the Angular 2 foreach loop before the array is modified by another function

Currently, I am facing some difficulties with an array that requires alteration and re-use within a foreach loop. Below is a snippet of the code: this.selectedDepartementen.forEach(element => { this.DepID = element.ID; if (this.USERSDepIDs. ...

Tips for integrating Reactjs with Chessboard.js

Recently, I stumbled upon chessboardjs (https://chessboardjs.com/) as a way to hone my React coding skills. However, I hit a roadblock while trying to implement a simple example of displaying the chess board in my application. The documentation instructed ...

What is the best way to incorporate multiple pages and export them in an angular2 project?

Having some issues with my code. Can anyone lend a hand? import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: `page1.html` }) @Component({ selector: 'my-app2', templateUrl: `page2.html` ...

Transferring information using TypeScript

My issue arises when transferring data from HTML in the following format Karbohidrat :{{karbohidrat}} <button ion-button (click)="cekHalamanMakanan('karbohidrat')">View carbohydrate foods</button> <br> Then, I retrieve the kar ...

Ways to obtain a reference to a different component

In my code, I have a component called componentA that displays the text "hello world". What I want to achieve is opening this component within another component named componentB by calling a function. Let's take a look at the code below: ComponentB. ...

Accessing data from an API and showcasing information on a chart using Angular

I'm currently developing a dashboard application that requires me to showcase statistics and data extracted from my MongoDB in various types of charts and maps using Angular and Spring Boot. The issue I'm facing is that when attempting to consume ...

What techniques can be used to determine which exact key was matched by a generic?

I am trying to find a method to deduce a more general string type key from a specific string that can be associated with it. type Foo = { [x: `/tea/${string}/cup`]: void; [x: `/coffee/${string}/time`]: void; [x: `/cake/${string}/tin`]: void; } type ...

Guide on implementing a cordova plugin in a TypeScript cordova application

In my Cordova project, which utilizes Angular and Typescript, I am facing issues with implementing the juspay-ec-sdk-plugin for Cordova. I have explored possible solutions on StackOverflow related to integrating Cordova plugin in an Angular 4 Typescript ...

NativeScript: TypeScript for Formatting Numbers

Being a beginner in NativeScript, I'm finding it difficult to find basic information through Google search. But now, I have a specific question: I have the number 1234567.89 stored in a variable, and I want to display it in a label with the format ...

Angular's GET request response is returning an "Undefined" value instead of the

As an Angular beginner, I've successfully set up and tested a service that retrieves data from a JSON file using the Get method. However, when attempting to access the data inside the JSON file, it returns as undefined. My goal is to use this data as ...

Verifying data types on combined function parameters

In the process of creating a function called getLocale(obj, key, locale), I aim to retrieve a specific locale from an object based on a given key. If the desired locale variant is not available, it should return a fallback option. While adding type checki ...

The signal property 'ɵunwrapWritableSignal' is not found on the specified type 'typeof import/node_modules/@angular/core/index")'

Despite attempting the solutions provided in previous threads, none of them have been successful for me. Can someone please lend a hand with this issue? https://i.stack.imgur.com/sGRsn.png ...

Encountering an error in Angular 4: 'Cannot find property on specified component type'

I recently embarked on the journey of learning Angular 4 and TypeScript, but I've encountered my first obstacle. My current challenge involves creating a simple date and time component. Despite having a seemingly correct Javascript code, I believe I ...