Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

405
Views
Angular: Using (click) and routerLink on the same Button

I have a button that redirects to a new page and at the same time should save data to a Service. As I use it now it looks like this:

<button [disabled]="!isValid" (click)="saveToService()" routerLink="/link">Next</button>

Now I wonder if this is best practice. It feels like the html button is somewhat cluttered by so many seperate functionalities. The obvious alternative is to move the router navigation to a function that does both things, as in:

<button [disabled]="!isValid" (click)="saveAndNavigate()">Next</button> and in ts:

private saveAndNavigate():void { this.service.setData(data); this.router.navigate(['/link]); }

Is there a 'right' way to do this? Are there some unwanted side effects from doing both actions in html?

Thanks

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

I would suggest you to do it in router promises. So you can:

this.router.navigate(['/link]).then(() => {
 this.service.setData(data);
});
over 4 years ago · Santiago Trujillo Report

0

I would implement the OnDestroy function in your component, so you can store the data when the component terminates.

Something like this in HTML:

<button [disabled]="!isValid" routerLink="/link">Next</button>

And like this in your component:

import { Component } from '@angular/core';

@Component({...})
export class ThisComponent implements OnDestroy {


    ngOnDestroy(){
        saveToService()
    }
}
over 4 years ago · Santiago Trujillo Report

0

If your navigation is performed regardless of the outcome of the service call, then Fatih's answer would work just fine.

On the other hand, and what I've normally seen, is that page navigation should only occur after (successful) completion of the request. If this is the case, I would remove the routerLink directive from your button and keep the (click) function. That function could look like this:


// if your service is making an Http request
public saveToService() {
  this.service.saveStuff().pipe(
    tap(() => this.router.navigate(['/somewhere']))
  )
}

tap simply performs some action without affecting the data stream, so it's perfect for router navigation.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!