Angular Changing/Replacing 基于用户选择的字符串中的值

Angular Changing/Replacing the value in a string based on the User selection

我正在制作一个录取通知书模板,该模板将根据从候选人列表中选择的候选人 replace/modify 动态数据点,例如姓名、地址、角色、薪水等。动态数据点有固定的语法,即它们将包含在 <<>> 中,例如:

Welcome to the family, <<Name>> 
You will be paid <<Salary>> for the duration of your employment. 

换句话说,这几个数据点将通过选择我们想要提供工作的候选人而改变,而模板的其余部分将保持不变。这里有一个demo to help you understand

这是我用 1 个模板创建的虚拟数组,在现实世界的应用程序中,我可以有许多具有不同 clauseNames 的模板,所以我正在寻找永久修复。 .ts 文件,模板列表:

[{

    templateId: 1,
    templateName: "Offer",
    clauses: [
      {
        clauseName: "Introduction",
        clauseId: 1,
        texts: [
          {
            text: "Hello <<Name>>, Welcome to the Machine",
            textId: 1,
          }]
      },
      {
        clauseName: "Address",
        clauseId: 2,
        texts: [
          {
            text: "<<Address>>",
            textId: 2,
          }]
      },
      {
        clauseName: "Date Of Joining",
        clauseId: 3,
        texts: [
          {
            text: "You can join us on <<DateOfJoining>>",
            textId: 3,
          }]
      },
    ]
  }]

这是候选人名单,

  candidateList = [
    { name: "Simba", address: "Some Random Cave" },
    { name: "Doe John", address: "line 4, binary avenue, Mobo" },
    { name: "B Rabbit", address: "8 mile road, Detroit" },
    { name: "Peter Griffin", address: "Spooner Street" },
    { name: "Speedy Gonzales", address: "401, hole 34, Slyvester Cat Road" },
    { name: "Morty", address: "Time Machine XYZ" },
    { name: "Brock", address: "pokeball 420, Medic center" },
  ]

您可以使用正则表达式来替换那些占位符,例如:

var result = text.text.replace(/\<\<(.*?)\>\>/g, function(match, token) {
       return candidate[token.toLowerCase()];
    });

将此合并到您的显示中的一种方法是创建一个 属性 returns 格式化文本。

我已经更新了你的stackblitz here

看看this demo

我修改了以下方法的逻辑:

  showTeplate(name,address,doj) {
    this.clauseList = [];
    for (let a of this.templateList) {
      if (a.clauses != null) {
        for (let cl of a.clauses) {
          const tempObj = JSON.parse(JSON.stringify(cl));
          tempObj.texts.forEach(textObj => {
            textObj.text = textObj.text.replace("<<Name>>",name);
            textObj.text = textObj.text.replace("<<Address>>",address);
            textObj.text = textObj.text.replace("<<DateOfJoining>>",doj);
          })
          this.clauseList.push(tempObj)

        }
      }
    }
    console.log("Clause list", this.clauseList)
  }