2017-06-30 65 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