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?
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 );
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
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With