Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Implement conditional Routing in Angular

I am trying to implement the following functionality. When a button is clicked to check a condition, condition should be a variable (or a sum in my case) different from undefined (if different then success). Then either go to the success-page if the condition is met or to display the fail page if the condition is not met (+ if nothing was changed in the page just go to the success-page).

.html

<div class="d-flex justify-content-center">

<button type="button" (click)="updatePost()" routerLink="/success-page">Save</button>

The updatePost() method in the .ts file simply calls a function from the service and updates a user if some properties are changed (I have some input textboxes in the .html file).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

updatePost() {
    this.sharedservice.updateUser(this.user).subscribe(response => {
}, error => {
    console.log(error);
    })
}

I tried many ways but the functionality is not correct. The problem might be the order in which I tried to call the function and implement the logic.

Both pages are registered as routes.

const routes: Routes = [
    {path: 'success-page', component: DisplaySuccessComponent},
    {path: 'fail-page', component: DisplayFailPageComponent},
];

>Solution :

For that you should use Router from constructor. For that you need to provide constructor(private router: Router) {} then you need to check variable should not be undefined, null or not expected condition, then you need to route like
this.router.navigate([‘fail-page’]); and if not undefined, not null and as expected condition then you can navigate by using this.router.navigate([‘success-page’]);. So, your final code like below:-

// In HTML:-

<button type="button" (click)="updatePost()">Save</button>

// In ts:-

updatePost() { 
    this.sharedservice.updateUser(this.user).subscribe(response => {
       this.router.navigate(['success-page']);
}, error => {
       this.router.navigate(['fail-page']);
    console.log(error);
    })
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading