简体   繁体   English

将值从 routerLink 传递给组件

[英]Passing a value from routerLink to Component

I have a Component with the following class:我有一个具有以下类的组件:

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

I am currently passing the value of stringToSubmit from the HTML this way:我目前正在通过这种方式从 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>

The end goal is to call the same component multiple times using routerLinks but to change stringToSubmit so that I get different data returned.最终目标是使用 routerLinks 多次调用同一个组件,但更改 stringToSubmit 以便我得到不同的数据返回。

I've redefined the string value in the Component, removing it from the @Input and assigning its type, but after hours of playing with it and trying to get different methods to work, I've come up empty:我在组件中重新定义了字符串值,将它从 @Input 中删除并分配了它的类型,但是在玩了几个小时并尝试使用不同的方法后,我发现它是空的:

export class MyCustomComponent implements OnInit {
    stringToSubmit: string;

The routing paths are defined as follows:路由路径定义如下:

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

I'm unsure where to add the values of stringToSubmit from this point to get it working.我不确定从这里开始在哪里添加 stringToSubmit 的值以使其正常工作。 I've looked into ActivatedRoute and defining the strings in multiple places including the path definitions and router links.我研究了 ActivatedRoute 并在多个地方定义了字符串,包括路径定义和路由器链接。 What am I missing?我错过了什么?

I'm assuming you want something like this:我假设你想要这样的东西:

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

or或者

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

To do this, you want a routing path like so:为此,您需要这样的路由路径:

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

and then update your component to include:然后更新您的组件以包括:

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

and

constructor(private route: ActivatedRoute) {}

And then do this OnInit :然后做这个OnInit

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM