DavidsAmause
DavidsAmause

Reputation: 57

How to Re-render specific component template from another component? Angular 2

I'm trying to re-render a angular 2 html template , so far after research I found that I need to use NgZone. So what I'm doing , in my main component I call navigation bar component , which calls userdetails component.

In the userdetails component is displaying the user details aka name and stuff. Im having another component which change the name of the user. So when I change the name there the name on the navigation bar ( userdetails component) dosen't change .

So I try that way in my change details component initialize a usedetails component and call a method from it which , initialize a ngZone and call the .run() method where I update the curretName with the new name ... and log in in the console.

SO when I update the name right after the http finish I receive in the console the new name but on the nav bar the name is still the same.

So far the only solution is window reload ... but this isn't user friendly since the user will not know what happened to the changes.

So I'm skipping something but what ?

Thanks in advance !

Upvotes: 0

Views: 1821

Answers (1)

AndreaM16
AndreaM16

Reputation: 3985

I think that trying to render again your component isn't the good way to solve your issue. You can solve it in two different ways:

  • Using a Getter/Setter service that returns an Observable so you can subscribe to it and get the changes you wish. So you would subscribe on that on your user-details.component and just set a new value using the setter with your navigation.component. You can read more on this article on Scotch.io by Jecelyn Yeen.

  • Using redux, so, for angular ngrx/store or ngrx/platform based on your angular version. With redux you'll be able to subscribe to an observable from your component, dispatch new events and more. It's pretty easy to implement what you need. Take a look at redux and the demos I linked above. I highly suggest you to watch this brilliant talk by Lukas Ruebbelke on youtube and look at his demo available here.

With both approaches, two way data binding will do the job, so, each time you are going to update your component's variables you'll see fresh data on your view.

Upvotes: 1

Related Questions