包装具有父/子关系的Angular组件 [英] Wrapping Angular components which has Parent/Child relationship
问题描述
我正在尝试使用自己的组件包装一些第三方组件(它们都是Angular 5组件)。
I'm trying to wrap some third-party components with my own components (All of them are Angular 5 components).
使用第三方组件时(不包装它们)我有以下代码:
When using the third-party component (without wrapping them) I have the following code:
<div>
<xyz-menubar>
<a xyzMenubarItem></a>
<a xyzMenubarItem></a>
</xyz-menubar>
</div>
我的目标是包装这些组件以使其具有以下代码:
My goal is to wrap these components to have the following code:
<div>
<app-menu>
<app-menu-item></app-menu-item>
<app-menu-item></app-menu-item>
</app-menu>
</div>
这就是我编码包装组件(将xyz菜单包装为应用程序菜单)的方式:
This is how I coded the wrapped components (xyz-menubar wrapped into app-menu):
@Component({
selector: 'app-menu',
templateUrl: './menu.component.html'
})
export class MenuComponent {
}
<div>
<xyz-menubar>
<ng-content></ng-content>
</xyz-menubar>
</div>
然后将xyzMenubarItem包裹到应用程序菜单项中:
And xyzMenubarItem wrapped into app-menu-item:
@Component({
selector: 'app-menu-item',
templateUrl: './menu-item.component.html'
})
export class MenuItemComponent {
}
<a xyzMenubarItem>
<ng-content></ng-content>
</a>
主要问题是第三方xyzMenubarItem组件取决于xyzMenubar(其父级),如您所见如下:
The main issue is that the 3rd party xyzMenubarItem component depends on xyzMenubar (its parent) as you can see below:
@Component({
selector: 'xyz-menubar-item, [xyzMenubarItem]',
template: `
<ng-content></ng-content>
`
})
export class MenubarItemComponent {
constructor(protected menubar: MenubarComponent, protected _elementRef?: ElementRef) {}
}
尝试使用包装好的组件(如开头所述的应用程序菜单和应用程序菜单项),出现以下错误:
When trying to use my wrapped components (app-menu and app-menu-item as described in the beginning), I get the following error:
ERROR Error: StaticInjectorError[MenubarComponent]:
StaticInjectorError[MenubarComponent]:
NullInjectorError: No provider for MenubarComponent!
at _NullInjector.get (core.js:923)
at resolveToken (core.js:1211)
at tryResolveToken (core.js:1153)
at StaticInjector.get (core.js:1024)
at resolveToken (core.js:1211)
at tryResolveToken (core.js:1153)
at StaticInjector.get (core.js:1024)
at resolveNgModuleDep (core.js:10585)
at NgModuleRef_.get (core.js:11806)
at resolveDep (core.js:12302)
我应该如何包装这些具有子/父项依赖性的第三方组件?
How should I wrap these 3rd party components that has child/parent dependency?
推荐答案
您可以通过在自定义应用程序菜单
组件上提供 MenuBarComponent
来解决此问题:
You can workaround it by providing MenuBarComponent
on you custom app-menu
component:
export function menuBarFactory(menu: MenuComponent) {
return menu.menuBar;
}
@Component({
selector: 'app-menu',
template: `
<div>
<xyz-menubar>
<ng-content></ng-content>
</xyz-menubar>
</div>
`,
providers: [
{
provide: MenuBarComponent,
useFactory: menuBarFactory,
deps: [MenuComponent]
}
]
})
export class MenuComponent {
@ViewChild(MenuBarComponent) menuBar: MenuBarComponent;
}
Stackblitz Example
这篇关于包装具有父/子关系的Angular组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!