6

I have a custom input component which implements ControlValueAccessor with providers declared as follows. It seems to work fine. In all the tutorials I could find on the internet, forwardRef was being used extensively whenever NG_VALUE_ACCESSOR is provided

Is it safe to send the following code to production ?

providers: [{
  provide: NG_VALUE_ACCESSOR,
  useExisting: CustomInputComponent,  //Notice I omitted forwardRef here and it works fine
  multi: true
}]
Surya KLSV
  • 1,180
  • 4
  • 16
  • 24

2 Answers2

2

forwardRef enables Angular to inject a dependency before it is defined. In this case, if this providers array is defined inside the @Component decorator for a custom input component as you mentioned, it will work since decorators are applied after the class is defined.

Basically, you can remove forwardRef as long as you are only using it to reference a component inside the decorator for that same component.

See here for in depth reading

Paul
  • 587
  • 1
  • 6
  • 17
1

The goal of forwardRef is to delay access to a class that is not defined at the time of execution current code.

It is not mandatory for your case because TypeScript transforms your code in a way when execution of decorator goes after class definition.

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;
})();
yurzui
  • 171,085
  • 24
  • 365
  • 354