Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4: How to update value of array in another component from another component

Tags:

angular

posts.component.ts - This is loaded in the router outlet in the AppComponent

PostsComponent {
    posts: any = [
            {
               'id': 1,
               'comment': 'Blah blah blah',
               'is_liked': false,
               'like_count' = 24,
            },
            {
               'id': 2,
               'comment': 'Yeah yeah yeah!',
               'is_liked': false,
               'like_count' = 24,
            }
        ]
}

posts-controls.component.ts - This is the child of the FooterComponent

PostControlsComponent {
    likePost('post_id'){
        //What do I do here
    }
}

If I run this method likePost(1); how do I update 'is_liked' to be 'true' and increment 'like_count' by 1 in the PostsComponent?

like image 683
Kabelo2ka Avatar asked Dec 08 '25 10:12

Kabelo2ka


1 Answers

You can use the Output decorator from @angular/core inside your PostControlsComponent to emit an event to the parent component, like:

 @Output()
 public onPostLiked = new EventEmitter<string>();
 ...
 public likePost(postId: string) {
    this.onPostLiked.emit(postId);
 }

And implement a onPostLiked method, which updates the likes of the post with postId.

public onPostLiked(postId: string) {
   let postToModify = this.posts.find(post => post.id === postId);
   if(postToModify) {
     postToModify.is_liked = true;
     postToModify.like_count += 1;
     // send some post request to back-end to inform about post count updated
   }
}

(OT: consider using camel-case (eg. like_count => likeCount) for your object attributes)

And for your HTML something like that:

<post-controls (onPostLiked)="onPostLiked($event)"></post-controls>

For more about component interaction you can read this: https://angular.io/guide/component-interaction

And also you should think about using a redux approach via @ngrx to keep your application state in one place (it is easier to debug and you can easily use the onPush ChangeDetectionStrategy).

https://medium.com/front-end-hacking/managing-state-in-angular-apps-with-ngrx-store-and-ngrx-effects-part-1-a878addba622

like image 150
cyr_x Avatar answered Dec 11 '25 13:12

cyr_x