1

In my project in the first component I have an input box, and a button.

    <div routerLink="questions" (click)="btnClicked(target.value)" class="button">Click Me</div>  

In the app.module.ts I set up the router, and it is working this way, but the problem is that in the btnClicked() function I'm checking if the user input is valid, and this way, it doesn't matter if the input is valid or not, the program will navigate to the questions component, so I'd like to do this routing in the typescript file, right after the validation.

Any suggestions? Thank you guys for the answer(s).

1
  • That is not good practice to do this.you can navigate to another route from btnclicked method. Commented Jul 11, 2018 at 8:03

2 Answers 2

1

use the navigateByUrl inside the button click function.

btnClicked(value){

  if(// your condition){
    this.router.navigateByUrl('questions')

  }
}

loose the routerLink from div

<div  (click)="btnClicked(target.value)" class="button">Click Me</div>  
Sign up to request clarification or add additional context in comments.

Comments

0

Remove the routerLink from the button element. And add the Router to the component constructor.

component.ts

import { Router } from '@angular/router';

constructor(private router: Router) {}

public btnClicked(event: any): void {
  if(this.valid) {   // check the validation here
     this.router.navigate(['/questions']);
  }
}

component.html

 <div (click)="btnClicked(target.value)" class="button">Click Me</div>  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.