1

I am building a navbar for my Angular app and I've decided to make a nav-item component for containing links inside of the navbar. I'd like to be able to pass a routerLink directive to it and have that directive get passed to the a element within the nav-item component.

My nav-item component looks like this.

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'nav-item',
  template: `
<li><a>
  <ng-content #wrapper></ng-content>
</a></li>
`
})
export class NavItemComponent implements OnInit {
  @ViewChild('wrapper') content: ElementRef;

  constructor() { }

  ngOnInit(): void {
  }
}

I want to be able to use the nav-item component like this.

<nav-item routerLink="/login">Login</nav-item>

Is there any way to pass to pass a routerLink directive from the nav-item component to its a element? Thanks in advance.

2 Answers2

1

Maybe I misunderstood your question. But you could do something like that

@Component({
  selector: 'nav-item',
  template: `
<li><a>
  <ng-content #wrapper></ng-content>
</a></li>
`
})
export class NavItemComponent implements OnInit {
  @ViewChild('wrapper') content: ElementRef;
  @Input('link') link: string;



  constructor() { }

  ngOnInit(): void {
      //Inject router on constructor
      this.rourter.navigate(link)
  }
}

And after that you call

<nav-item link="/login">Login</nav-item>
Rafael Andrade
  • 495
  • 1
  • 5
  • 22
1

This should also work, and it should support passing a string link or URL tree.

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'nav-item',
  template: `
<li><a [routerLink]="routerLink">
  <ng-content></ng-content>
</a></li>
`
})
export class NavItemComponent implements OnInit {
  @Input() routerLink: string | any[];

  constructor() { }

  ngOnInit(): void {
  }
}

As a side note, unless you absolutely need the ElementRef, you should not use it for security reasons. Please read the note about it here: https://angular.io/api/core/ElementRef

Richard Schibly
  • 437
  • 2
  • 7