Search code examples
angularngrxangular9

How to get data in Child Components using Angular 9 and NGRX?


I am creating a project with Angular 9 and NGRX and I have the following page component:

@Component({
  template: `
    <div *ngFor="let post of posts$ | async">
      {{ post.name }}
    </div>
    <top-posts></top-posts>
  `
})
export class PostsPageComponent {

  posts$: Observable<Post[]> = this.store.select(state => state.posts);

  constructor(private store: Store<{ posts: Post[] }>) {}

  ngOnInit() {
    this.store.dispatch({ type: '[Posts Page] Load Posts' });
  }

}

In this component I have a Child Component that displays TopPosts.

I believe I should add topPosts: Post[] to my Store and an action '[Posts Page] Load Top Posts'.

But how should I access this data in my child component?

  1. Should I inject the store in child component and use:

     this.store.dispatch({ type: '[Posts Page] Load Top Posts' });
    
  2. Should I pass the data from PostPageComponent into TopPostsComponent?

    How? And in this case should I change action to '[Top Posts Component] Load Top Posts'?


Solution

  • In my opinion, you can dispatch the actions for your child components in the parent component and pass the result as @Input to your child components.

    This way your child component need not have any dependency on the store and can act as presentational components.