Angular-将指令插入同一元素的其他指令

时间:2019-06-05 12:56:11

标签: angular

假设我有这段代码

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

是否可以将RouterLinkActive指令实例插入我的appTab指令中?

1 个答案:

答案 0 :(得分:1)

如果使用ViewContainerRefs.createEmbeddedView used correct injector会更容易,但是目前我们只能解决它。

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