我的自定义表格组件有一个全选指令。我希望我的指令的用户能够以两种方式实例化它:
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/