在创建NG_VALUE_ACCESSOR时是否必须使用forwardRef

问题描述 投票:3回答:2

我有一个自定义输入组件,该组件使用声明如下的提供者来实现ControlValueAccessor。似乎工作正常。我可以在网上找到的所有教程中,只要提供NG_VALUE_ACCESSOR,就会广泛使用forwardRef]

将以下代码发送到生产环境安全吗?

providers: [{
  provide: NG_VALUE_ACCESSOR,
  useExisting: CustomInputComponent,  //Notice I omitted forwardRef here and it works fine
  multi: true
}]
angular dependency-injection controlvalueaccessor
2个回答
0
投票

forwardRef使Angular可以在定义依赖项之前注入它。在这种情况下,如果您在自定义输入组件的@Component装饰器中定义了这个provider数组,那么它将起作用,因为在定义类之后应用了装饰器。

基本上,您可以删除forwardRef,只要您仅在组件的装饰器中使用它即可。

See here for in depth reading


0
投票

forwardRef的目标是延迟对在执行当前代码时未定义的类的访问。

对于您的情况,这不是强制性的,因为TypeScript transforms装饰器的执行在类定义之后执行的方式来编写您的代码。

let CustomInputComponent = /** @class */ (() => {
    var CustomInputComponent_1;
    let CustomInputComponent = CustomInputComponent_1 = class CustomInputComponent {
    };
    CustomInputComponent = CustomInputComponent_1 = __decorate([
        Component({
            selector: 'app-custom-input',
            template: '<input />local: {{val}}',
            providers: [
                {
                    provide: NG_VALUE_ACCESSOR,
                    useExisting: CustomInputComponent_1, // already defined!!!
                    multi: true
                }
            ]
        })
    ], CustomInputComponent);
    return CustomInputComponent;
})();
© www.soinside.com 2019 - 2024. All rights reserved.