是否有Angular 2等效于Angular 1&$ 39的内插?我想获取一个字符串和一个对象,并能够用该对象的值替换字符串中的标记。
示例:
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作为字符串模板?
答案 0 :(得分:5)
关于类似问题的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 );
答案 1 :(得分:4)
Angular 2没有内置此功能,但您可以构建一个,例如在本文中:
http://weblogs.thinktecture.com/pawel/2016/04/angular-2-interpolation-service.html
Typescript DOES具有此功能,因此如果您使用typescript来构建Angular 2应用程序,则可以使用它:
https://basarat.gitbooks.io/typescript/content/docs/template-strings.html
答案 2 :(得分:3)
在打字稿中,您可以使用模板字符串进行插值。模板字符串由后面的刻度线环绕,值由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"
语句环绕。以下是您提供的字符串示例:
Private Shared ReadOnly MyPropertyPropertyKey As DependencyPropertyKey = DependencyProperty.RegisterReadOnly("MyProperty", GetType(List(Of FrameworkElement)), GetType(MyUserControl), New FrameworkPropertyMetadata(New List(Of FrameworkElement)()))
Public Shared ReadOnly MyPropertyProperty As DependencyProperty = MyPropertyPropertyKey.DependencyProperty
Public ReadOnly Property MyProperty() As List(Of FrameworkElement)
Get
Return CType(GetValue(MyPropertyProperty), List(Of FrameworkElement))
End Get
End Property