Interpolate a row with dynamic data using angular2

I download data from the server through ajax requests. The JSON file has configurations for pop-ups on the site.

popupData: {
   data:{ var_one: "hello", var_two: "world"},
   template: "the <b>{{var_two}}</b> say {{var_one}}"
}

Variable names and patterns will be different for each popup.

How can I get this row interpolated by data with it? I need to pass a pre-built string to a component that will be viewed using [innerHTML].

+6
source share
1 answer

Somewhere after receiving the data:

const popupString = popupData.template.replace(
  /{{\s?([^{}\s]*)\s?}}/g,
  (substring, parsedKey) => {
    const replacer = popupData.data[parsedKey];
    return typeof replacer !== 'undefined' ? replacer : substring;
  }
);

It should equal the <b>world</b> says Helloin your example.

Please note that this code comes from robisim74s angular -l10n (MIT license).

+3

Source: https://habr.com/ru/post/1016446/


All Articles