【问题标题】:How to display only one formArray object?如何只显示一个 formArray 对象?
【发布时间】:2022-08-14 21:38:17
【问题描述】:

我目前正在构建一个反应表单组,用户可以在其中输入成分。最初,用户可以输入一种成分(名称、重量、公制单位),然后在保存成分时, 出现一个新的输入字段,他们可以在其中添加另一种成分。这在技术上效果很好,但我想在输入字段之外显示成分,如果用户单击正在显示的成分行,他们就可以对其进行编辑。

这是我制作的模型,绿色文本是表单数组输入字段的占位符。

这是我显示 formArray 的方式:

<ng-container formArrayName=\"ingredients\">
 <ng-container *ngFor=\"let ingredient of ingredients.controls; let i = index\">
  <div class=\"ingredient-container\" [formArrayName]=\"i\">
   <div class=\"ingredient-row\">
    <input
      class=\"input ingredient-text\"
      formControlName=\"name\"
      type=\"text\"
      placeholder=\"Name\"
    />
    <div class=\"ingredient-row\">
      <input
        formControlName=\"weight\"
        type=\"text\"
        class=\"input ingredient-text\"
        placeholder=\"Weight\"
      />
      <input
        class=\"input ingredient-text\"
        formControlName=\"metricUnit\"
        type=\"text\"
        placeholder=\"Metric Unit\"
      />
    </div>
  </div>
</div>

这就是它目前的样子

我知道 *ngFor 正在迭代存储在 FormArray 中的所有当前成分,这就是它显示两次的原因。我想使用表单数组,因为我想保留我所做的所有验证,但似乎这已成为一项不可能完成的任务。有没有可行的方法来做到这一点?

任何指导表示赞赏。

    标签: html angular angular-reactive-forms formarray


    【解决方案1】:

    您只需考虑到您的 FormArray 是 FormGroups 的 FormArray,因此只需创建一个函数

    indexSelected:number=-1
    getGroup(index:number)
    {
       return this.ingredients.at(index) as FormGroup
    }
    

    并使用

    <form *ngIf="indexSelected!=-1" [formGroup]="getGroup(indexSelected)">
    ...
    </form>
    

    您需要使用变量 indexSelected “播放” - 请参阅从 0 到 your-formArray.controls.length-1 的值 -

    注意:使用时请注意

    <ng-container *ngFor="let ingredient of ingredients.controls; let i = index">
        <!..see that you has a type error is formGroupName, not formArrayName-->
      <div class="ingredient-container" [formGroupName]="i">
          ...
      </div>
    </ng-container>
    

    是“喜欢”你使用

    <ng-container *ngFor="let ingredient of ingredients.controls; let i = index">
      <div class="ingredient-container" [formGroup]="ingredients.at(i) as FormGroup">
          ...
      </div>
    </ng-container>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-11
      相关资源
      最近更新 更多