【问题标题】:Dynamic from fields using reactive forms in Angular?使用Angular中的反应形式从字段动态?
【发布时间】:2021-11-19 18:59:58
【问题描述】:

我有一个场景,比如需要编辑单引号值(只有单引号值),

所以我使用正则表达式提取了单引号值并准备了反应式动态表单。

单击执行编辑按钮会在上面显示旧步骤名称,下面显示新步骤名称,提交步骤将替换原始数组中的步骤名称。

根据我的方法,在少数场景中工作正常,但在场景中,我意识到我遵循的任何算法都不能满足我的要求。

下面是测试用例

测试用例 1: 步骤名称:“那么我应该使用‘美国’的个人资料‘1’雇用一名员工”, // 这里 --> '1', 'USA' 值是可编辑的

测试用例 2:“应在 'Current' Fiscal 的工资期 '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

所以谁能给我建议如何解决这个问题,

提前致谢

【问题讨论】:

    标签: javascript arrays angular angular-forms angular10


    【解决方案1】:

    我添加了一个名为 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

    【讨论】:

      猜你喜欢
      • 2019-02-23
      • 2018-10-10
      • 1970-01-01
      • 2019-12-05
      • 1970-01-01
      • 2020-05-13
      • 2017-05-05
      • 2018-07-15
      • 1970-01-01
      相关资源
      最近更新 更多