Angular2 如何仅在父组件存在时将其注入(inject)指令?

标签 angular typescript angular2-directives

我的自定义表格组件有一个全选指令。我希望我的指令的用户能够以两种方式实例化它:

1:

<my-custom-table>
    <input type="checkbox" my-select-all-directive/>
</my-custom-table>

2:

<input type="checkbox" [table]="myTableRef" my-select-all-directive/>
<my-custom-table #myTableRef></my-custom-table>

我能够通过在指令的构造函数中使用 Host、Inject 和 forwardRef 获得第一种工作方式:

constructor(@Host() @Inject(forwardRef(() => MyCustomTableComponent)) table?: MyCustomTableComponent) {
    this.table = table; //later I can call this.table.selectAll();
}

但是当我以第二种方式实例化它时,我得到一个异常,提示没有 MyCustomTableComponent 的提供者,大概是因为 MyCustomTableComponent 在第二种实例化方式中不是父级,所以 Host 和 forwardRef 什么都不返回......

如何使该参数成为可选参数?所以我的指令使用它的父或祖父 MyCustomTableComponent(如果它存在),否则使用传递给它的任何表作为输入...

最佳答案

您可以使用 @Optional() 装饰器将依赖项设为可选:

constructor(@Optional() @Host() @Inject(forwardRef(() => MyCustomTableComponent)) table?: MyCustomTableComponent) {
    this.table = table; //later I can call this.table.selectAll();
}

关于Angular2 如何仅在父组件存在时将其注入(inject)指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39082634/

相关文章:

angular - 如何添加到当前路线并导航 - Angular

javascript - 当方法可能会或可能不会异步获取数据时,应使用哪种 RxJS 类型?

html - 在 typescript 中带有 foreach 的模板电子邮件 html

angular - 将选择标签数据绑定(bind)到Angular中的 react 形式

javascript - 如何将指令绑定(bind)到 angular2 中的函数?

javascript - 如何在一个指令上使用多个 ngFor 进行属性绑定(bind)

angular - ionic 4 - 动态改变导航过渡方向

响应式表单中的 Angular 表单组与表单控件和表单生成器

typescript - 如何在本地项目中为 JavaScript 库创建类型定义?

angular - NgFor 不使用 Angular2 中的管道更新数据