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.