angular - 使用父组件扩展的类注入父组件
问题描述
我有多个不同的角度分量。在许多这些组件中还有一个基本列表组件。
举个例子:VegetablesComponents 有一个 BaseListComponent,FruitsComponent 有 BaseListComponent 等等……当然,在 Vegetables/Fruits 组件中也有不同的子组件。
BaseListComponent 从父组件(VegetablesComponent、FruitsComponent)获取一些修改某些功能的数据。这是使用 BaseListComponent 上的 @Input() 完成的。
所以我想到了蔬菜组件,水果组件可以扩展同一个类。我可以在 BaseListComponent 中注入父组件。让我们说:
VegetablesComponents extends HasBaseFunctionality {}
然后在 BaseListComponent 中,我将使用构造函数(父级:HasBaseFunctionality,...)。
这将减少 BaseList 组件所需的输入数量,并使其看起来更干净。
但是一旦我尝试这样做,我得到了:
StaticInjectorError(AppModule)[ChildComponentComponent ->
BaseComponentComponent]:
StaticInjectorError(Platform: core)[ChildComponentComponent ->
BaseComponentComponent]:
NullInjectorError: No provider for BaseComponentComponent!
如果我会使用:
constructor(parent: VegetablesComponent) {...}
它会起作用的。
所以我想知道是否有任何方法可以在不使用服务的情况下执行此操作,一旦初始化,我将在该服务上注册当前的基本组件,然后使用服务访问它的值。
解决方案
您的每个子组件都需要提供父类:
@Component({
providers: [
{
provide: BaseComponentComponent,
useExisting: VegetablesComponent
}
]
})
然后就可以正常注入BaseComponentComponent
类型了。
推荐阅读
- python - 如何过滤掉包含 NaN 或 '-' 的行?
- apache-spark - 在Java Spark中重新分区后如何找出每个分区中的项目
- javascript - VUE:如何在 CSS 模块中使用 prop?
- angular - 为什么在更新到 Angular 8 后将 eventlistner 添加到我的动态创建的图像中会在页面加载时触发
- node.js - 从 mongodb 获取最新记录,如果这两条记录相同但时间不同
- html5-video - 视频无法在 HTML5 播放器中播放
- minizinc - Minizinc:在决策变量中声明显式集
- swift - @GestureState 不能用作属性
- c# - 如何使 radgridview 或 datagridview 中的外键字段成为用户可以选择的下拉列表?
- delphi - 我是否需要释放这些框架,如果是,这是正确的方法吗?