Search code examples
angularcomponentsngx-editor

Angular ngx-editor outsource config from app.component.ts in other components.ts file


LiveDemo with Code see here https://stackblitz.com/edit/ngx-editor

In this project you can see in the document app.component.ts that the variable editorConfig contains the configuration of the editor.

I want to outsource this variable in a file, because I want to load a different configuration depending on the purpose of use.

If I create a componente, the page does not load. How can I create an ngx-config-component.ts which only contains the variable and how can I integrate this configuration afterwards?

Thank you very much for your help Christoph


Solution

  • I don't really understand why you need to separate this into a separate file but it would probably be best to use Angular's Dependency Injection mechanism. I made a fork on stackblitz as an example: https://stackblitz.com/edit/ngx-editor-ecaqtx

    I created a new service in the file config.service.ts:

    import { Injectable } from '@angular/core';
    
    @Injectable()
    export class ConfigService {
      editorConfig = {
        editable: true,
        spellcheck: false,
        height: '10rem',
        minHeight: '5rem',
        placeholder: 'Type something. Test the Editor... ヽ(^。^)丿',
        translate: 'no'
      };
    }
    

    Registered it in the app.module.ts:

    ...
    import { ConfigService } from './config.service';
    
    @NgModule({
      imports: [BrowserModule, FormsModule, HttpClientModule, NgxEditorModule],
      declarations: [AppComponent, HelloComponent],
      bootstrap: [AppComponent],
      providers: [AppService, ConfigService]
    })
    export class AppModule { }
    

    And then used it in the app.component.ts:

    ...
    import { ConfigService } from './config.service';
    ...
    
      constructor(private _appService: AppService, private _configService: ConfigService) { 
        this.editorConfig = _configService.editorConfig;
      }
    ...
    

    You can learn more about Angular's DI here: https://angular.io/guide/dependency-injection

    Another approach to the problem could be to pass the configuration as a data argument using the Angular Router so you could have different configurations using the same component, just on different routes. You can learn more here: https://angular.io/guide/router#router-state