Angular2 如何仅在父组件存在时将其注入指令?
Angular2 how to inject parent component into directive only if it's there?
我的自定义 table 组件有一个 select-all 指令。我希望我的指令的用户能够以两种方式实例化它:
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 return 没什么...
如何使该参数可选?所以我的指令使用它的父或祖父 MyCustomTableComponent 如果它存在,或者使用任何 table 传递给它作为输入...
您可以使用 @Optional()
装饰器使依赖项可选:
constructor(@Optional() @Host() @Inject(forwardRef(() => MyCustomTableComponent)) table?: MyCustomTableComponent) {
this.table = table; //later I can call this.table.selectAll();
}
我的自定义 table 组件有一个 select-all 指令。我希望我的指令的用户能够以两种方式实例化它:
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 return 没什么...
如何使该参数可选?所以我的指令使用它的父或祖父 MyCustomTableComponent 如果它存在,或者使用任何 table 传递给它作为输入...
您可以使用 @Optional()
装饰器使依赖项可选:
constructor(@Optional() @Host() @Inject(forwardRef(() => MyCustomTableComponent)) table?: MyCustomTableComponent) {
this.table = table; //later I can call this.table.selectAll();
}