Search code examples
angulartypescriptangular-directiveangular-routerlink

Angular passing directive to child element


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.


Solution

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