woodykiddy
woodykiddy

Reputation: 6455

Refresh the parent component view in Angular 4

I have got 2 components, let's say, Component A is a list view and Component B is a details view. Each row from the list view is clickable and will redirect to Component B upon clicking.

Component B allows editing and saving the details. I have added a Back button to Component B to allow me to go back to the list view.

But the problem I am having is that I can't see the updated list view and have to manually refresh the browser, and then I can see the updated list there.

I have tried directly using window.location and it works but really I don't prefer this approach.

public back() {
   window.location.assign('/listview');
}

I wonder if there's any better way to solve this problem?

Update:

public onSelected(model: MyModel) {
    const detailsViewUrl = `/detailsview/${model.id}`;
    this._router.navigateByUrl(detailsViewUrl );
  }

Upvotes: 2

Views: 5445

Answers (5)

Rancio
Rancio

Reputation: 165

You can just emit an @Output EventEmitter with a method on Parent that looks in the event for a change with a variable stored in the component like this:

@Output someOutput: EventEmitter = new Event Emitter<any>;

HTML:

  <b-component (someOutput)=getOutput($event)></b-component>

AComponent:

 getOut(event){
     let output = event;
     if(this.something != output){
          this.ngOnDestroy(); // or something that you can use to make it
    }

That should work as intended.

Upvotes: 1

hyper0009
hyper0009

Reputation: 246

Seems like a change detection issue, there are some ways to manually trigger change detection like so:

  1. Inject ChangeDetectorRef.

  2. Call it when you go back like so:

    public back() {
       ChangeDetectorRef.detectChanges()
    }
    

Refer to this: Triggering change detection manually in Angular

Upvotes: 0

Karthic G
Karthic G

Reputation: 1182

Try this,

Just called the list view again internally and hit db at same time so updated values will be displayed in the list view.

calling the route by using below:

this.router.navigate(['/listview']);

Upvotes: 0

mittal bhatt
mittal bhatt

Reputation: 1009

use following routing fuction on back button click

public back() {
   this._router.navigateByUrl('/listview')
}
or
public back() {
   this._router.navigate('/listview')
}

Upvotes: 0

Plog
Plog

Reputation: 9622

It sounds like this is an issue with Angular's change detection when changing the contents of an array. See here:

Angular 2: How to detect changes in an array? (@input property)

The solutions in this questions should work but an easy way I have used in the past to force changes in an array to be recognised by Angular is to reassign the array after making the changes:

myArray = [...myArray];

Upvotes: 0

Related Questions