Search code examples
angularangular2-routing

How to redirect to a new page in Angular 4 through button click?


In home.component.html page I want the button to redirect the url to a new page when clicked.

I expect that when I clicked the button, the current url http://localhost:24282/home, will be redirected to this url http://localhost:24282/master and master.component.html page will be shown.

The issue is that, though the url is redirected to http://localhost:24282/master when I clicked the button, but still I'm on the current page home.component.html. I wasn't completely redirected to the master page master.component.html

Below are the implementation.

app.routing.ts

    import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './Components/home.component';
import { MasterComponent } from './Components/master/master.component';
import { PageNotFoundComponent } from "./Components/common/page-not-found.component";

const appRoutes: Routes = [
    { path: 'home', component: HomeComponent },
    { path: 'master', component: MasterComponent },
    { path: '', redirectTo: 'home', pathMatch: 'full' },
    { path: '**', component: PageNotFoundComponent }
];

export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);

app.module.ts

    import { NgModule } from '@angular/core';
import { APP_BASE_HREF } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { routing } from './app.routing';
import { HomeComponent } from './Components/home.component';
import { MasterComponent } from './Components/master/master.component';
import { PageNotFoundComponent } from "./Components/common/page-not-found.component";

@NgModule({
    imports: [BrowserModule, routing],
    declarations: [AppComponent, HomeComponent, MasterComponent, PageNotFoundComponent],
    providers: [{ provide: APP_BASE_HREF, useValue: '/' }],
    bootstrap: [AppComponent]
})
export class AppModule {}

app.component.ts - where the newChange() method is defined

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

@Component({
    selector: 'moc-landing',
    templateUrl: './app/Components/home.component.html',
    styleUrls: ['./app/Components/home.component.css']
})
export class AppComponent {
constructor(private router: Router) {}

    newChange(): void {
        this.router.navigateByUrl('master');
    }
}

home.component.html

<button id="new" class="btn btn-primary" (click)="newChange()">New Change Request</button>

I'm not sure if I have correctly used router.navigateByUrl or is there any alternative way?

In ASP.NET MVC, this is fairly easy to do using razor's URL helper classes (e.g. @Url.Action).

But in Angular 4 (which I'm pretty new to it), I don't know how to implement it. I have gone through some research, but couldn't find any related to this.

Any help is greatly appreciated.


Solution

  • If you are using a link (<a>), you only need the routerLink directive/parameter:

    <a class="btn" routerLink="/votes">Check votes</a>
    

    If you are using a button (<button>), you need a (click) event:

    <button class="btn" (click)="goToVotes()">Check votes</button>
    

    It is preferable to create a function/method in this case, since it is a good practice to keep private parameters in your component's constructor, i.e. don't use router.navigate() directly on your HTML (avoids 'router' warnings due to using a private member of the component).

    import { Component } from '@angular/core';
    import { Router } from '@angular/router';
    // component details here...
    export class MyComponent  {
      constructor(private router: Router){ }
    
      goToVotes($myParam: string = ''): void {
        const navigationDetails: string[] = ['/votes'];
        if($myParam.length) {
          navigationDetails.push($myParam);
        }
        this.router.navigate(navigationDetails);
      }
    }
    

    The goToVotes method above will also add a second value to the navigate's array if its argument is not empty, and thus:

    <button class="btn" (click)="goToVotes('ca')">Go vote</button>
    

    Would redirect to /votes/ca.