Angular 2 – Reload component when routerLink clicked again

All we need is an easy explanation of the problem, so here it is.

I am working on Angular 2 project with following file structure.

  • HeaderComponent.ts
  • AppComponent.ts
  • Page1Component.ts
  • Page2Component.ts

I have following template in my HeaderComponent.ts

<nav class="navbar navbar-default navbar-fixed-top" role="navigation">
    <div class="container-fluid">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#" rel="nofollow noreferrer noopener">WebSiteName</a>
        </div>
        <div class="collapse navbar-collapse" id="myNavbar">
            <ul class="nav navbar-nav">
                <li class="active"><a [routerLink]="['']">Home</a></li>
                <li><a [routerLink]="['/page1']" >Page1</a></li>
                <li><a [routerLink]="['/page2']">Page2</a></li>
            </ul>
        </div>
    </div>
</nav>

with following routes in my AppComponent

@Component({
    selector: 'my-app',
    template: ` 
            <my-header></my-header>
            <router-outlet></router-outlet>
    `,
    directives: [ROUTER_DIRECTIVES, HeaderComponent]
})
@Routes([
    {path: '/', component: HomeComponent},
    {path: '/page1', component: Page1Component}
    {path: '/page2', component: Page2Component}
])
export class AppComponent {
    ngAfterViewInit() {
        //To show the active tab in navbar
        $(".nav a").on("click", function () {
            $(".nav").find(".active").removeClass("active");
            $(this).parent().addClass("active");
        });
    }
}

and my Page1Component has following sample form

<section class="col-md-8 col-md-offset-2">
    <form [ngFormModel]="myForm" (ngSubmit)="onSubmit()">
        <div class="form-group">
            <label for="firstName">First Name</label>
            <input [ngFormControl]="myForm.find('firstName')" type="text" id="firstName" class="form-control">
        </div>
        <div class="form-group">
            <label for="lastName">Last Name</label>
            <input [ngFormControl]="myForm.find('lastName')" type="text" id="lastName" class="form-control">
        </div>
        <div class="form-group">
            <label for="email">Mail</label>
            <input [ngFormControl]="myForm.find('email')" type="email" id="email" class="form-control">
        </div>
        <div class="form-group">
            <label for="password">Password</label>
            <input [ngFormControl]="myForm.find('password')" type="password" id="password" class="form-control">
        </div>
        <button type="submit" class="btn btn-primary" [disabled]="!myForm.valid">Sign Up</button>
    </form>
</section>

So when I click on Page1 routerLink in header <li><a [routerLink]="['/page1']">Page1</a></li>, it loads the Page1Component in <router-outlet></router-outlet>. I fill some details in form and when I click on Page1 routerLink again in header before submitting the form, I want Page1Component to reload so my form comes to initial state but it doesn’t do anything on click. I tried to reset form in routerOnActivate() and routerCanDeactivate() but none of the functions being called. So basically, I want my component to load again when I click on [routerLink]

Please let me know if I can explain better.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You can take care of this scenario by using dummy route,

<a (click)="changeRoute(url)">

Add one dummy route to your router:

{ path: 'dummy', component: dummyComponent }

dummyComponent.ts

//Dummy component for route changes

@Component({
    selector: 'dummy',
    template: ''
})
export class dummyComponent{}

Now inside your component add changeRoute function:

changeRoute(url) {
  this.router.navigateByUrl('/dummy', { skipLocationChange: true });
  setTimeout(() => this.router.navigate(url));
}
// 'skipLocationChange' will avoid /dummy to go into history API

This will re render your component and rest all will be taken care by Angular.

Method 2

You could use the (click) event an navigate in code to some dummy component and then again back to the previous component. There is a parameter in router.navigate() to skip history changes so the back button keeps working with this hack.

Method 3

Another approach would be to remove the routerLink, and naviagate via code:

<a (click)="gotoPage1()">

Now gotoPage1 just appends a #X number to existing url

...
count: number = 2;
gotoPage1(){
 count++;
 return this.router.navigate(...'#'+count);
}

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply