将值从routerLink传递到Component

时间:2018-02-22 02:43:07

标签: angular angular2-routing

我有一个包含以下类的Component:

export class MyCustomComponent implements OnInit {
    @Input('stringToSubmit') stringToSubmit:string;

我目前正在以这种方式从HTML传递stringToSubmit的值:

<app-my-custom stringToSubmit="definedString"></app-my-custom>
<app-my-custom stringToSubmit="definedString2"></app-my-custom>
<app-my-custom stringToSubmit="definedString3"></app-my-custom>

最终目标是使用routerLinks多次调用同一个组件,但更改stringToSubmit以便我返回不同的数据。

我已经重新定义了Component中的字符串值,将其从@Input中删除并指定了它的类型,但是在玩了几个小时并尝试使用不同的方法之后,我就空了:

export class MyCustomComponent implements OnInit {
    stringToSubmit: string;

路由路径定义如下:

const routes: Routes = [
    { path: 'path-url', component: MyCustomComponent }
];

我不确定从这一点开始在哪里添加stringToSubmit的值以使其正常工作。我查看了ActivatedRoute并在多个位置定义了字符串,包括路径定义和路由器链接。我错过了什么?

1 个答案:

答案 0 :(得分:1)

我假设你想要这样的东西:

[routerLink]="['path-url', stringToSubmit]"

routerLink="path-url/{{stringToSubmit}}"

为此,您需要一个如此的路由路径:

const routes: Routes = [
    { path: 'path-url/:stringToSubmit', component: MyCustomComponent }
];

然后更新您的组件以包含:

import { Router, ActivatedRoute } from '@angular/router';

constructor(private route: ActivatedRoute) {}

然后执行此操作OnInit

public ngOnInit(): void {
    this.route.params.subscribe(params => {
        this.stringToSubmit = params.stringToSubmit;
    });
}
相关问题