Search code examples
angularangular-providers

unable to assign const value in useValue


I've created a const class ElementConst

export class ElementConst {
    public static LINK = 'LINK';
    public static HEADING_1 = 'heading-1';
    public static HEADING_2 = 'heading-2';
    public static HEADING_3 = 'heading-3';
    public static HEADING_4 = 'heading-4';
    public static HEADING_5 = 'heading-5';
    public static HEADING_6 = 'heading-6';
    public static PARAGRAPH = 'paragraph';
    public static STRONG = 'BOLD';
}

So I've imported this class in my module and trying to assign it useValue

export const CONTENT_MAPPINGS_PROVIDER: Provider = [
  {
    provide: CONTENT_MAPPINGS,
    useValue: {
      ElementConst.HEADING_1: HeadingComponent, // trying to do something like this, which throws error
      'heading-2': HeadingComponent,
      'heading-3': HeadingComponent,
      'heading-4': HeadingComponent,
      'heading-5': HeadingComponent,
      'heading-6': HeadingComponent,
      'paragraph':ParagraphComponent
    }
  }
];

Why I'm unable to assign values inside useValue ?


Solution

  • When specifying a key that is dynamic, you need to wrap it in [].

    Here's a bare-bones example of how to make your code pass the compiler:

    export class ElementConst {
        public static LINK = 'LINK';
        public static HEADING_1 = 'heading-1';
        public static HEADING_2 = 'heading-2';
        public static HEADING_3 = 'heading-3';
        public static HEADING_4 = 'heading-4';
        public static HEADING_5 = 'heading-5';
        public static HEADING_6 = 'heading-6';
        public static PARAGRAPH = 'paragraph';
        public static STRONG = 'BOLD';
    }
    
    interface Provider {
      provide: any;
      useValue: any;
    }
    
    const HeadingComponent = {};
    const ParagraphComponent = {};
    
    export const CONTENT_MAPPINGS_PROVIDER: Provider[] = [
      {
        provide: '',
        useValue: {
          [ElementConst.HEADING_1]: HeadingComponent,
          'heading-2': HeadingComponent,
          'heading-3': HeadingComponent,
          'heading-4': HeadingComponent,
          'heading-5': HeadingComponent,
          'heading-6': HeadingComponent,
          'paragraph': ParagraphComponent,
        }
      }
    ];