2017-09-04 160 views
0

我有路由通過我的Angular web-app中的菜單設置。菜單上有routerLinks建立像下面的主頁鏈接:角度4功能,調用路由

<a routerLink="home"> 
      <button md-menu-item> 
       <md-icon class="material-icons"> home </md-icon> 
       <span> Home </span> 
      </button> 
     </a> 

的app.router包含:

export const router: Routes = [ 
    { path: '', redirectTo: 'home', pathMatch: 'full'}, 
    { path: 'home', component: HomeComponent }, 
]; 

我想有一個重定向到一個查詢表格組件的按鈕,是不是在正常菜單中可用,但在組件中的按鈕上放置鏈接似乎不起作用。爲什麼是這樣?

對我來說,理想的做法是將一個函數放置在調用路由的組件的html元素中 - 這可能嗎?

回答

1

如果我理解正確,那當然是可以的。

只需添加路由器到您的組件構造:

constructor(private router: Router) {} 

,然後你可以調用從你的函數Router類將點擊按鈕後,被稱爲導航功能,例如:

this.router.navigate(['home']); 

另一種可能性是將[routerLink]放在html標記中:

<a [routerLink]="['/home']">Go To Home</a> 

檢查:

https://angular.io/guide/router

https://angular.io/api/router/Router

+0

的一個LINKWAY工作正常,但我更願意理解第一種方法。我收到一條錯誤信息,說導航不可用。然後我導入路由器,但我的app.router只導入路由和路由器模塊 - 有沒有辦法解決這個問題? – Davtho1983

+0

@ Davtho1983你能發表這個錯誤嗎? – porgo

+0

好吧,奇怪的是,我似乎現在都有這兩種方法 - 我必須犯了一個語法錯誤!謝謝你的幫助 :) – Davtho1983