【发布时间】:2020-01-12 07:46:38
【问题描述】:
Tl;dr:如何提供可见组件作为指令的依赖项?自然,组件必须在指令之前初始化,但它必须与应用程序稍后在组件的 selector 上运行时显示的实例相同。
详情:
我的 app.component.html 的结构如下:
app.component.html
<app-navigation></app-navigation>
<router-outlet></router-outlet>
顶部有一个始终可见的导航栏。 <router-outlet> 始终显示当前活动的组件。
我现在想允许<router-outlet> 中呈现的组件修改导航栏的内容,例如显示适合当前活动组件的附加按钮。这应该与指令一起使用,如下所示:
some.component.html
<div *appTopBar>
<button>Additional Button</button>
</div>
附加按钮现在应该出现在顶部的导航栏中。
appTopBar 指令如下所示:
top-bar.directive.ts
import {AfterViewInit, Directive, OnDestroy, TemplateRef} from '@angular/core';
import {AppComponent} from '../navigation/navigation.component';
@Directive({
selector: '[appTopBar]'
})
export class TopBarDirective implements AfterViewInit, OnDestroy {
constructor(private tmpl: TemplateRef<any>,
private nav: NavigationComponent) {
}
ngAfterViewInit(): void {
this.nav.setTopBarContent(this.tmpl);
}
ngOnDestroy(): void {
this.nav.setTopBarContent(null);
}
}
该指令对NavigationComponent有依赖,可以通过公开提供的方法setTopBarContent()向导航栏传递内容:
navigation.component.ts
import {Component, EmbeddedViewRef, TemplateRef, ViewChild, ViewContainerRef} from '@angular/core';
@Component({
selector: 'app-navigation',
templateUrl: './navigation.component.html',
styleUrls: ['./navigation.component.scss']
})
export class NavigationComponent {
@ViewChild('topBarContainer',{static: false})
topBar: ViewContainerRef;
topBarContent: EmbeddedViewRef<any>;
constructor() {}
/**
* Set the template to be shown in the top bar
* @param tmpl template, null clears the content
*/
public setTopBarContent(tmpl: TemplateRef<any>) {
if (this.topBarContent) {
this.topBarContent.destroy();
}
if (tmpl) {
this.topBarContent = this.topBar.createEmbeddedView(tmpl);
}
}
}
我遇到的第一个问题是,在初始化 TopBarDirective 时,NavigationComponent 依赖项还不可用。我收到以下错误:
错误错误:未捕获(承诺):NullInjectorError:
StaticInjectorError(AppModule)[TopBarDirective -> NavigationComponent]: StaticInjectorError(Platform: core)[TopBarDirective -> NavigationComponent]:
NullInjectorError: 没有 NavigationComponent 的提供者!
所以显然组件在指令之后被初始化并且还不可用。
我尝试将NavigationComponent 添加到AppComponent 的providers 数组中,并且依赖注入现在起作用了:
@NgModule({
declarations: [
NavigationComponent,
SomeComponent,
TopBarDirective
],
imports: [
BrowserModule,
CommonModule
],
providers: [NavigationComponent]
})
export class AppModule { }
但是,现在似乎有两个 NavigationComponent 实例。我通过在NavigationComponent 的constructor 中生成一个随机数并记录它来检查这一点。该指令肯定有一个与<app-navigation> 选择器显示的实例不同的实例。
现在我知道这种模式以某种方式起作用。前段时间我发现它是由一些 Angular 开发人员介绍的,但不幸的是我不再有源代码了。然而,工作版本显示AppComponent 中的内容,因此该指令仅依赖于AppComponent,它似乎首先被初始化。因此,不会发生整个依赖性问题。
如何确保提供给TopBarDirective 的NavigationComponent 实例与<app-navigation> 选择器中显示的实例相同?
【问题讨论】:
标签: angular typescript angular-directive angular-dependency-injection