Sno*_*ugg 5 typescript angular2-directives angular
我的自定义表格组件有一个全选指令。我希望我的指令的用户能够通过两种方式实例化它:
1:
<my-custom-table>
<input type="checkbox" my-select-all-directive/>
</my-custom-table>
Run Code Online (Sandbox Code Playgroud)
2:
<input type="checkbox" [table]="myTableRef" my-select-all-directive/>
<my-custom-table #myTableRef></my-custom-table>
Run Code Online (Sandbox Code Playgroud)
我能够通过在指令的构造函数中使用 Host、Inject 和forwardRef 获得第一种工作方式:
constructor(@Host() @Inject(forwardRef(() => MyCustomTableComponent)) table?: MyCustomTableComponent) {
this.table = table; //later I can call this.table.selectAll();
}
Run Code Online (Sandbox Code Playgroud)
但是当我以第二种方式实例化它时,我收到一个异常,抱怨没有 MyCustomTableComponent 的提供程序,大概是因为 MyCustomTableComponent 不是第二种实例化方式中的父级,因此 Host 和forwardRef 不返回任何内容...
我怎样才能使该参数可选?因此,我的指令使用其父级或祖级 MyCustomTableComponent(如果存在),或者使用传递给它的任何表作为输入...
您可以使用装饰器将依赖项设置为可选@Optional():
constructor(@Optional() @Host() @Inject(forwardRef(() => MyCustomTableComponent)) table?: MyCustomTableComponent) {
this.table = table; //later I can call this.table.selectAll();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3068 次 |
| 最近记录: |