Input Subject is empty in child component Angular 17

Discussão em 'Angular' iniciado por Ems, Novembro 27, 2024.

  1. Ems

    Ems Guest

    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?

    Continue reading...

Compartilhe esta Página