简体   繁体   中英

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:

<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.

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:

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. I've looked into ActivatedRoute and defining the strings in multiple places including the path definitions and router links. 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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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