javascript - 使用Angular中的 react 形式从字段动态?

标签 javascript arrays angular angular-forms angular10

我有一个场景,比如需要编辑单引号值(只有单引号值),
因此,我使用正则表达式提取了单引号值并准备了响应式(Reactive)动态表单。
onclick 执行编辑按钮将在上面显示旧步骤名称,下面显示新步骤名称,提交步骤将替换原始数组中的步骤名称。
根据我的方法,在少数场景中工作正常,但在场景中,我意识到我遵循的任何算法都不能满足我的要求。
下面是测试用例
测试用例 1:
步骤名称:“那么我应该使用‘美国’的个人资料‘1’雇用一名员工”,
//这里 --> '1', 'USA' 值是可编辑的
测试用例 2:“应在‘当前’财政的‘01’工资期‘01’日雇用员工”
//'01', '01', '当前'
问题:在测试用例 2 中,如果我尝试编辑第二个 01,它正在编辑第一个 01
我尝试借助 indexof、子字符串函数来解决执行编辑功能

this.replaceString = this.selectedStep.name;
this.metaArray.forEach((element: any) => {
  var metaIndex = this.replaceString.indexOf(element.paramValue);
  if (metaIndex !== -1) {
    const replaceValue = this.stepEditForm.controls[element['paramIndex']].value;
    this.replaceString = this.replaceString.substring(0, metaIndex) + replaceValue + this.replaceString.substring(metaIndex + (element.paramValue.length));
  }
});
但在 indexof 中总是找到字符串中第一次出现的值。所以我意识到我的方法在执行它的功能上是错误的
请找到代码的附件
https://stackblitz.com/edit/angular-reactive-forms-cqb9hy?file=app%2Fapp.component.ts
所以任何人都可以向我建议如何解决这个问题,
提前致谢

最佳答案

我添加了一个名为 matchStartingPositions 的函数,它返回每个匹配项的起始位置索引。使用此方法,您可以像您一样通过替换字符串来执行编辑,但我们会在给定位置找到要替换的正确匹配。
所以在你的行中

var metaIndex = this.replaceString.indexOf(element.paramValue);
然后我们可以向 indexOf 添加第二个参数,即起点:
var metaIndex = this.replaceString.indexOf(element.paramValue, startingPositions[element.paramIndex]);
获取索引位置的函数只是在给定字符串中查找那些单引号:
matchStartingPositions(str) {
    let count = 0;
    let indices = [];
    [...str].forEach((val, i) => {
      if (val === "'") {
        if (count % 2 == 0) {
          indices.push(i);
        }
        count++;
      }
    });
    return indices;
  }
这是在行动:
https://angular-reactive-forms-xhkhmx.stackblitz.io
https://stackblitz.com/edit/angular-reactive-forms-xhkhmx?file=app/app.component.ts

关于javascript - 使用Angular中的 react 形式从字段动态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69349802/

相关文章:

javascript - 如何将数据从 Node 发送到另一台服务器

时间:2019-03-17 标签:c++: Help correcting endless loop while modifying c-string array

angular - 返回单个字符的 Switchmap - Angular

javascript数组长度为1

javascript - 基于现有 div 的触发代码

javascript - 将图像裁剪为宽高比 1 :1

arrays - 如何提取字典键中的键

python - 如何在 Python 中访问 N 维数组的部分?

angular - NG2 : How can I access parent component generically?

angular - docker cloud上Angular 2上的net::ERR_CONTENT_LENGTH_MISMATCH