首页 文章

Angular 2相当于$ interpolate

提问于
浏览
5

Angular 2是否相当于Angular 1的$ interpolate?我想获取一个字符串和一个对象,并能够用该对象的值替换字符串中的标记 .

例:

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"

我可以写一些能为我做这件事的东西,但如果可能的话,我更愿意使用内置的角度方式 .

EDIT:

我应该提到插值需要能够用字符串变量发生 . 我知道typescript / es6对文字字符串有反向插值,但我需要插入存储在变量中的模板字符串 . 也许有一种方法可以在我不知道的变量中使用插值内置的typescript作为字符串模板?

3 回答

  • 3

    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

  • 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"
    
  • 4

    关于类似问题的一个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 );
    

相关问题