假设我有这段代码
<div *appTab routerLink="..." routerLinkActive="..."></div>
是否可以将RouterLinkActive
指令实例插入我的appTab
指令中?
答案 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>