2017-02-17 50 views
3

是否存在與Angular 1的$ interpolate相當的Angular 2?我想要一個字符串和一個對象,並能夠用對象中的值替換字符串中的標記。

例如:

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" 

我可以寫的東西會爲我做到這一點,但我更願意使用一個內置的角度的方式,如果可能的。

編輯:

我應該提到的是,插值需要能夠與字符串變量發生。我知道typescript/es6對文字字符串有反向插值,但是我需要插入存儲在變量中的字符串模板。也許有一種方法可以在我不知道的變量中使用爲插入字符串模板插入內置的typescript?

回答

2

在打字稿,您可以使用模板字符串做插值。模板字符串通過反標記環繞,值由${}語句環繞。這裏是你提供的字符串的一個例子:

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" 
+0

嗨,感謝您的回答,我忘了提,我需要插值從發生變量。我現在添加了一個編輯解釋。也許有一種方法可以使用變量進行打字稿插值? – tt9

3

上的類似問題進行comment向我指出Lodash庫,它是template功能。

添加Lodash到您的項目:

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

然後,在你的.ts文件:

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);