7

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

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

providers: [{
  provide: NG_VALUE_ACCESSOR,
  useExisting: CustomInputComponent,  //Notice I omitted forwardRef here and it works fine
  multi: true
}]
4

2 回答 2

4

forwardRef使 Angular 能够在定义之前注入依赖项。在这种情况下,如果此提供程序数组是在@Component您提到的自定义输入组件的装饰器中定义的,那么它将起作用,因为装饰器是在定义类之后应用的

基本上,只要您只使用它来引用同一组件的装饰器内的组件,您就可以删除。forwardRef

请参阅此处进行深入阅读

于 2020-05-27T16:33:47.230 回答
2

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

对于您的情况,这不是强制性的,因为 TypeScript会在执行装饰器后执行类定义时转换您的代码。

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;
})();
于 2020-05-27T16:34:08.113 回答