Angular 2 - Reload component when routerLink click

2019-04-29 21:39发布

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="#">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.

3条回答
倾城 Initia
2楼-- · 2019-04-29 22:08

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.

查看更多
爷、活的狠高调
3楼-- · 2019-04-29 22:25

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.

查看更多
我命由我不由天
4楼-- · 2019-04-29 22:25

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);
}
查看更多
登录 后发表回答