Search code examples
angularngx-editor

How can I make the toolbar options for 'ngx-editor' dynamically formatted in the variable or constant form in Angular?


import { Editor, Toolbar } from 'ngx-editor';

toolbar: Toolbar = [['bold', 'italic', 'bullet_list', 'ordered_list']];

I want to store the above toolbar values as constants or variables. Expected behaviour -

Case 1: Make it as constants and use it.

text-formatting.const.ts

export const TEXT_FORMATTING_TYPE = {
    BOLD: 'bold',
    ITALIC: 'italic',
    BULLET_LIST: 'bullet_list',
    ORDERED_LIST: 'ordered_list'
}

abc.component.ts

import {TEXT_FORMATTING_TYPE} from '../../constants';

toolbar: Toolbar = [[ TEXT_FORMATTING_TYPE.BOLD, TEXT_FORMATTING_TYPE.ITALIC, TEXT_FORMATTING_TYPE.BULLET_LIST, TEXT_FORMATTING_TYPE.ORDERED_LIST]];

Case 2: Make it as variables and use it.

abc.component.ts

bold: ToolbarItem;
italic: ToolbarItem;
bulletList: ToolbarItem;
orderedList: ToolbarItem;
toolbar: Toolbar = [[ this.bold, this.italic, this.bulletList, this.orderedList ]];

I tried both ways but, nothings seems to be working. Could anyone help me find the solution for this ? Thank you.


Solution

  • Just type cast the values to ToolbarItem[], this will solve your issue!

    ...
    toolbar: Toolbar = [
        <ToolbarItem[]>[
          TEXT_FORMATTING_TYPE.BOLD,
          TEXT_FORMATTING_TYPE.ITALIC,
          TEXT_FORMATTING_TYPE.BULLET_LIST,
          TEXT_FORMATTING_TYPE.ORDERED_LIST,
        ],
        ...
    

    Alternative will be to set the type to TBItems, which will also work!

    import { TBItems } from 'ngx-editor';
    
    export const TEXT_FORMATTING_TYPE: { [key: string]: TBItems } = {
      BOLD: 'bold',
      ITALIC: 'italic',
      BULLET_LIST: 'bullet_list',
      ORDERED_LIST: 'ordered_list',
    };
    

    Stackblitz Demo