user2180794
user2180794

Reputation: 1455

Angular 2 - How to pass routeparams in routerConfig without reloading the page

How to pass routeparams in routerConfig without reloading the page

I have a component which is passing routerparams in the routerlink as follows

@Component({
    selector: 'apartment',
  template: `
   <div *ngFor="#apartment of apartments" class="demo-updates mdl-card mdl-shadow--2dp mdl-cell mdl-cell--4-col mdl-cell--4-col-tablet mdl-cell--12-col-desktop">
              <div class="mdl-card__actions mdl-card--border">                
                <a [routerLink]="['AptDetails', {UnitType: apartment.UnitType, aptStatus: 'Available'}]" class="mdl-button mdl-js-button mdl-js-ripple-effect" (click)="getAvailable(apartment)">Available</a>                            
              </div>
    </div>   

In the receiving component the parameters are read as follows,

@Component({
    selector: 'aptdetails',
  template: ` <h1> Apt Details</h1>
              {{aptDetails | json}} 
    `,
    directives: [ROUTER_DIRECTIVES]
})

export class AptDetailsComponent implements OnInit {

    constructor(private apartmentService: ApartmentService, private sharedService: SharedService, params: RouteParams) {
    this.apartmentService = apartmentService;
    this.aptStatus = params.get('aptStatus');
    this.UnitType = params.get('UnitType');    
    }

The values are passed successfully, but the page is refreshed.

How can I pass the parameters without refreshing the page in routerLink ?

I know that we can create a shared service for temporary storage of the values between components, How can I use routeparams for the same ?

Upvotes: 2

Views: 181

Answers (2)

Arun Tyagi
Arun Tyagi

Reputation: 2256

use CanReuse and OnReuse, as

export class Component implements  OnReuse, CanReuse {

    routerCanReuse() {
        if (yourCondition)
            return true;
        else
            return false;
    }

    routerOnReuse() {
        console.log('on reuse');
    }


}

Upvotes: 0

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658067

You can implement CanReuse

class MyComponent implements CanReuse {
  routerCanReuse(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction) {
    return true;
  }
}

then navigating to the current route with only parameters changed does reuse the existing component instance.

Upvotes: 1

Related Questions