LppEdd
LppEdd

Reputation: 21134

Angular - inject directive into other directive for the same element

Let's say I have this piece of code

<div *appTab routerLink="..." routerLinkActive="..."></div>

Is it possible to inject the RouterLinkActive Directive instance into my appTab Directive?

Upvotes: 0

Views: 2003

Answers (1)

yurzui
yurzui

Reputation: 214067

It would be easier if ViewContainerRefs.createEmbeddedView used correct injector but for now we can only workaround it.

router-link-active-tab-connector.directive.ts

import { Directive, Input, OnInit } from '@angular/core';
import { TabDirective } from './tab.directive';
import { RouterLinkActive } from '@angular/router';

@Directive({
  selector: '[routerLinkActive][routerLinkActiveTabConnector]'
})
export class RouterLinkActiveLinkerDirective implements OnInit {
  @Input('routerLinkActiveTabConnector') tab: TabDirective;

  constructor(private routerLinkActive: RouterLinkActive) {}

  ngOnInit() {
    this.tab.setRouterLinkActive(this.routerLinkActive);
  }
}

tab.directive.ts

import { Directive, ViewContainerRef, TemplateRef } from '@angular/core';
import { RouterLinkActive } from '@angular/router';

@Directive({
  selector: '[appTab]'
})
export class TabDirective {

  constructor(private vcRef: ViewContainerRef, private templateRef: TemplateRef<any>) { }

  setRouterLinkActive(routerLinkActive: RouterLinkActive) {
    console.log(routerLinkActive);
    // do something with RouterLinkActive directive
  }

  ngOnInit() { 
    this.vcRef.createEmbeddedView(this.templateRef, { $implicit: this});
  }
}

html

<div *appTab="let tabRef" 
  routerLink="..." 
  routerLinkActive="" 
  [routerLinkActiveTabConnector]="tabRef">
   Some content
</div> 

Ng-run Example

Upvotes: 3

Related Questions