2017-08-02 35 views
1

使用相對路徑這是我的文件夾結構:路由編程到其他組件中Angular2/4

App 
    -KitchenComponent 
     -css 
     -html 
     -kitchen.component.ts 
    -BedroomComponent 
     -css 
     -html 
     -kitchen.component.ts 
app.component.html 
app.component.ts 

我想從廚房組件移到臥室組件編程方式使用相對路徑。

KitchenComponent.html 
<button (click)="moveToBedroomComponent()"></button> 

KithcenComponent.ts 
Constructor(private router: Router){} 
moveToBedroomComponent(){ 
    this.router.navigate(['bedroom'], {relativeTo:_____}); 
} 

我覺得我被困在給這裏的相對路徑,輸入讚賞。

+0

嘿,有什麼不清楚[我的回答](https://stackoverflow.com/a/45453582/2545680)? –

回答

1

relativeTo參數爲基準,以激活路線:

所有的
@Component({...}) 
class KitchenCmp { 
    constructor(private route: ActivatedRoute, private router: Router) { 
    } 

    moveToBedroomComponent(){ 
    this.router.navigate('../bedroom', {relativeTo:this.route}); 
    } 
} 
+0

最大值,當你插入'../'時它變成絕對路徑,對吧? –

+0

@MichaelPhilips,不,它是相對於當前路線 –

+0

感謝接受,所以它工作好嗎? –

1

首先,這將是很好看你app.route.ts文件。

我做導航這樣的: this._router.navigate(['dashboard']);

app.route.ts包含{path: 'dashboard', component: HomeComponent, canActivate: [AuthGuard]}

另外,還要確保您的進口是正確的: import { Router, ActivatedRoute } from '@angular/router';

編輯

你確定你需要relativeTo位在你的router?乍一看,你似乎沒有。

相關問題