Code Junkie
Code Junkie

Reputation: 83

How do I pass in a property into a link to a component in Angular

I have this link in my app.component.html...

<a [routerLink]="['system-administration/error-management']">Error Management</a>

I want to be able to pass in a title property into a link on the app component to another component that that component would display on its html page like this...

<h1>{{ title }}</h1>

I tried doing this...

<a [routerLink]="['system-administration/error-management']" [test]="Error Management">Error Management</a>

But that didn't work.

The error I got when I did ng serve was this...

Can't bind to 'test' since it isn't a known property of 'a'

I know I can create a global file and put all the properties in there, then import that global file into each component to access the property I want that way, but I think it would be more succinct if I were able to simply pass in a property where there is a link to a component.

Is this possible in Angular 11?

Thanks in advance!

Upvotes: 1

Views: 719

Answers (1)

Maya Glazer Sharabi
Maya Glazer Sharabi

Reputation: 142

you can use the string in the url params on the other component;

import {Router, ActivatedRoute, Params} from '@angular/router';
import {OnInit, Component} from '@angular/core';

@Component({...})
export class MyComponent implements OnInit {

title: string;

  constructor(private activatedRoute: ActivatedRoute) {}

  ngOnInit() {
    this.activatedRoute.params.subscribe(params => {
        const message = params[0];
        this.title = message;
      });
  }

}

Upvotes: 1

Related Questions