Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use routes in submit button form - Angular2

I'm new to Angular2 and I have been having some doubts about routes.

I'm using Angular Material and I have 2 forms: Login and Signup. When I click Submit in one of those forms I want to be redirected to a component called Portal.

This is my structure and each component has its own module:

  • App
    • Form
      • Login
      • Signup
    • Portal

I thought I could make it work with routerLink but I realized soon enough that it wasn´t possible. I know that I have to pass some event to the ngSubmit, but I'm not sure what...

If someone could explain me the process and guide me through the steps, I'd be very thankful.

Thank you.

like image 480
fcff94 Avatar asked May 22 '17 12:05

fcff94


2 Answers

  • In the html use ngSubmit and will just need to call a function like below

    <form (ngSubmit)="onSubmit()">
    
  • Define the router in '@angular/router'

    import {Router} from '@angular/router';
    
  • In the controller put

    onSubmit() {
        this.router.navigateByUrl('/portal');
    }
    

Hope this helps

like image 57
Jalay Oza Avatar answered Oct 11 '22 10:10

Jalay Oza


First you need to import

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

Then inject it in the constructor

constructor(private router: Router) {}

Then either user ngSubmit event on the form or click event on the button, add the method and at the end of it do this.

this.router.navigate(['/portal']);
like image 24
Tunisiano32 Avatar answered Oct 11 '22 10:10

Tunisiano32