I am trying to pass data from a parent to its child component in Angular 17. The data is retrieved from the back-end through an API that gets an array of items.
In my parent component, items$ is a subject:
items$ = Subject<Array<Item>> = new Subject();
I subscribe it to the method of my service that retrieves all items from the backend:
ngOnInit(){
this.itemService.getItems().subscribe(this.items$);
}
In my parent.html template, this code does display that there are items:
@if(items$ | async){
"There are items!"
}@else{
"There aren't any items"
}
So I then call my child component:
@if(items$ | async){
<app-child [items$]=items$>
}
This is what my child.component.ts looks like:
export class ChildComponent implements OnInit{
@Input() items$: Observable<Array<Item>>;
ngOnInit(){
this.items$.subscribe();
}
}
An child.component.html:
@if(items$ | async){
"There are items in the child component!"
}@else{
"There aren't any items in the child component"
}
Well, it displays that there aren't any items in the child component.
I know I don't need to subscribe in the onInit() method of my child component, but I really just wanted to make sure that I am indeed subscribed to my multicast observable.
Also, interestingly, when I take my child component out of the @if condition in parent.html, the items are displaying!
Any idea why? And how can I condition the display of my child component to the presence of items?
this.itemService.getItems().subscribe(this.items$)this piece of code looks really strange, what are you trying to achieve with this?.subscribe(), instead of a callback function, you can also pass anObserverobject instead which has optional properties fornext,errorandcomplete. So when passing aSubject, it will call thenextfunction of that subject. Never seen this, but pretty neat.