Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 equivalent to $interpolate

Tags:

string

angular

Is there an Angular 2 equivalent to Angular 1's $interpolate? I want to take a string and an object and be able to replace tokens in the string with values from the object.

example:

let myTemplateStr = "Hello {{user.name}}, you are {{user.age.years}} years old"

//use the Angular2 equivalent of interpolate
let myTemplateCompiled = Angular2.Interpolate(myTemplateStr, { 
    user: { 
        name: "bob", 
        age: {
            years: 10
        }
     }})
//myTemplateCompiled ends up becoming "Hello bob, you are 10 years old"

I could write something that would do this for me but I would prefer to use a built in angular way if possible.

EDIT:

I should have mentioned that the interpolation needs to be able to to happen with string variable. I know typescript/es6 have backtick interpolation for literal strings, but I need to interpolate a string templated stored in a variable. Perhaps there is a way to use typescript built in interpolation for a string template in a variable that I am unaware of?

like image 270
tt9 Avatar asked Feb 17 '17 20:02

tt9


3 Answers

A comment on a similar question pointed me to Lodash library and it's template function.

Add Lodash to your project:

$ npm install --save lodash
$ npm install --save @types/lodash

Then, in your .ts file:

import * as _ from "lodash";

let myTemplateStr = "Hello {{user.name}}, you are {{user.age.years}} years old";

let myVariables = {
    user: { 
        name: "bob",
        age: { 
            years: 10
        }
    }
}

// use custom delimiter {{ }}
_.templateSettings.interpolate = /{{([\s\S]+?)}}/g;

// interpolate
let compiled = _.template( myTemplateStr );
let myTemplateCompiled = compiled( myVariables );
like image 110
evo Avatar answered Oct 08 '22 01:10

evo


Angular 2 does not have this feature built in, but you could build one, such as in this article:

http://weblogs.thinktecture.com/pawel/2016/04/angular-2-interpolation-service.html

Typescript DOES have this feature, so you can use it if you're using typescript to build your Angular 2 application:

https://basarat.gitbooks.io/typescript/content/docs/template-strings.html

like image 34
chrispy Avatar answered Oct 08 '22 01:10

chrispy


In typescript you can use template strings to do the interpolation. Template strings are surround by back ticks and the values are surround by ${} statements. Here is an example of the string you provided:

let user: { 
    name: "bob", 
    age: {
        years: 10
    }
};
let myTemplateCompiled = `Hello ${user.name}, you are ${user.age.years} years old`;
//myTemplateCompiled ends up becoming "Hello bob, you are 10 years old"
like image 22
Teddy Sterne Avatar answered Oct 08 '22 01:10

Teddy Sterne