Chris Owens
Chris Owens

Reputation: 58

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?

Upvotes: 2

Views: 6586

Answers (1)

Simon K
Simon K

Reputation: 2857

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;
    });
}

Upvotes: 1

Related Questions