Search code examples
angularresourcesdynamic-text

Angular 2+ Dynamic UI Text


I'm developing an app which is not multilingual, yet the client is asking to be able to change the labels, texts and even notifications through an admin interface. So I though of resource file that can be fetched from the server on app load and bind all labels, texts and notifications.

Not sure if something is out there already implemented or if there a better way of achieving this. I've ng2-translate but it won't serve the purpose of changeable text through admin screen.

Thank you.


Solution

  • All text can be displayed using template binding, e.g. {{ myLabel }}. myLabel in turn can be assigned based on a request to a server that takes a language parameter or you can have locally stored values which are used if a certain language setting is selected. The server option is more manageable IMO.

    async setText(languageId: number) {
      this.text = await this.http.get('yourUrl', {
        params: { languageId: languageId.toString()} }).toPromise();
    }
    

    Text could be an object with all your text, e.g.

    "text": [
     "notifications": ["warningNotification": "whatever", ... 
    ] 
    

    You could display these throughout the template:

    <div id="warningDiv">{{ text?.notifications?.warning }}</div>
    

    And follow the same pattern throughout, with a different text json object delivered depending on the language.

    Notice the question marks which are safety operators to avoid null errors while the request is processing.