2017-06-30 62 views
1

美好的一天,Angular 2 |不能在路由組件上使用屬性綁定

任何人都可以告訴我什麼是綁定路由組件的屬性的替代方法嗎?看起來@input()裝飾器不能在路由組件上工作。

謝謝

+0

你可以分享你的代碼?雖然有人已經給出了答案,但如果您可以提供代碼 – brijmcq

+0

是什麼讓您認爲它不起作用,那將會更有幫助? –

+0

你可以參考我的另一個問題。我想要的是我想要將類屬性綁定到子組件。 https://stackoverflow.com/questions/44817467/angular-2-i-cant-bind-property-from-another-class?noredirect=1#comment76615953_44817467 –

回答

0

嘗試使用路由器參數。因此,在您的路由器配置中,有像這樣的組件的路由器路徑(被視爲「MyComponent」);

routes: Routes = [ { path: 'mycomponent/:myParam', component: MyComponent} ]

然後將實際值傳遞給HTML中錨點標記中的路由器,如:

<a [routerLink]="['/mycomponent', paramValue]"> Link to MyComponent </a>

或在你的父組件,導航到編程MyComponent的;

this.router.navigate(['/mycomponent', paramValue]);

而在你的組分(MyComponent的),從角度路由器,它提供了一個PARAMS可觀察導入ActivatedRoute,以及訂閱該可觀察到的在ngOnInit方法。所以你的MyComponent應該看起來像這樣;

import { Component, OnInit, OnDestroy } from '@angular/core'; 
import { ActivatedRoute } from '@angular/router'; 


@Component({ 
    selector: 'my-selector', 
    template: '<div>My Component - Param Value {{myParamValue}}</div> ' 
}) 

export class MyComponent implements OnInit, OnDestroy{ 
myParamValue: any; 
private subscribe: any; 

constructor(private route: ActivatedRoute){} 

ngOnInit() { 
    this.subscribe= this.route.params.subscribe(params => { 
     this.myParamValue = params['myParam']; 
    }); 
    } 

ngOnDestroy() { 
    this.subscribe.unsubscribe(); 
    } 
} 

更多here

+0

這與屬性綁定相同嗎?所以在這個例子中,你正在發送myParamValue到激活的路由器鏈接?到你目前的路線在哪裏? –

+0

當您具有應該綁定到組件屬性的模板屬性值時,應用屬性綁定。如果您必須傳遞給組件的數據類似於ID,則可以使用此方法。否則,請使用通用服務在這些組件之間共享數據 – HashanMadz