Reputation: 1257
I have a list of menu items and when i click on them the display content changes and that all works fine but i also want to be able to update the url path with the selected tab and i wanted to know how can i update my current list to use any available given angular 2 feature.
current code:
<ul class="nav nav-tabs">
<li [class.active]="isTab('home')">
<a (click)="setTab('home')">Home</a>
</li>
<li [class.active]="isTab('contacts')">
<a (click)="setTab('contacts')">Contacts</a>
</li>
....
</ul>
<home-view *ngIf="isTab('home')"></home-view>
<contacts-view *ngIf="isTab('contacts')"></contacts-view>
...
I would like so whenever i click on either home or contacts tab that the url path gets updated to ..../home or ..../contacts so the user will be able to navigate back to it if they were to navigate away.
I am using angular 2 with typescript
Upvotes: 0
Views: 859
Reputation: 5731
You should resort to routes then.
i.e. in app.module.ts
const appRoutes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full'},
{ path: 'home', compoennt: HomeViewComponent, pathMatch: 'full'},
{ path: 'contacts', compoennt: ContactsViewComponent, pathMatch: 'full'},
{ path: '**', component: HomeViewComponent },
];
@NgModule({
declarations: [],
imports: [
...,
RouterModule.forRoot(appRoutes, { enableTracing: false }),
],
exports: [...]
],
providers: [],
bootstrap: [AppComponent]
})
Then in your component html, add a router-outlet
<ul class="nav nav-tabs">
<li [class.active]="isTab('home')">
<a (click)="setTab('home')">Home</a>
</li>
<li [class.active]="isTab('contacts')">
<a (click)="setTab('contacts')">Contacts</a>
</li>
....
</ul>
<router-outlet>
and in your component ts you can control the route by inject router
constructor(private router: Router) {}
setTab(newTab: string) {
this.router.navigate([newTab]);
}
Upvotes: 0
Reputation: 58533
This is not a proper way , if you want the url and nvaigation link to work
Please go for route instead of using ngIf to show hide compoenents
routes = [
...
{ path : 'home' , compoenent : HomeComponent },
{ path : 'contacts' , compoenent : ContactsComponent },
...
];
Template Side :
<ul class="nav navbar-nav">
<li><a routerLink="/home" routerLinkActive="active" >About</a></li>
<li><a routerLink="/contact" routerLinkActive="active" >Contact</a></li>
</ul>
<router-outlet></router-outlet>
To add a certain class based on if a certain route is active, we can use
routerLinkActive
For more detail : Watch this
Upvotes: 2