嵌套在另一个FormArray中的FormArray

问题描述 投票:4回答:1

[这里是我要完成的工作:

在页面中,用户将能够上传其对某些外汇对的保护。因此,用户可以选择不同的时间范围来上传他们的图像分析。我的表格很简单:

dataForm: FormGroup;
this.dataForm = this.builder.group({
      nombre: ['', [Validators.required]],
      analisis: this.builder.array([ this.createItems() ])
    });

为了创建分析数组,我使用此代码:

createItems() {
    return this.builder.group({
      temporalidad: [],
      descripcion: [],
      fileImg: this.builder.array([])
    });

  }

一切正常,直到我必须为我创建的不同分析选择图像为止。如果我只是选择添加另一张分析卡[分析1和分析2],如果我使用按钮加载要分析的图像,则该图像会正确显示在分析1卡的...中,但是当我选择分析图像时2,这显示在分析1卡的而非分析2卡的

这是我用于加载图像的代码

fileUploads(evt: any, index: any) {
    const files = evt.target.files;
    const control = this.dataForm.controls.analisis['controls'][index].controls['fileImg'].controls;
    for (let i = 0; i < files.length; i++) {
      const reader = new FileReader();
      reader.onload = (e) => {
        const base64img = reader.result + '';
        control.push(this.builder.control(base64img));
      };
      reader.readAsDataURL(files[i]);
    }
    evt.srcElement.value = null;
  }

以及用于显示图像的HTML

<div>
                                <label for="file-upload" class="custom-file-upload">
                                    <mat-icon class="icon">add_a_photo</mat-icon> Imagen del análisis
                                </label>
                                <input id="file-upload" name="file" type="file" (change)="fileUploads($event, i)" accept="image/png,image/jpeg,image/jpg"/>
                            </div>
                            <figure *ngFor="let image of dataForm.controls.analisis['controls'][i].controls['fileImg'].controls; let j = index" style="margin-left: 0px;">
                                <img [src]="image.value" class="proyection-image" />
                            </figure>

我还发布了Stackblitz链接,以供您查看功能并更好地了解我要存档的内容。StackBlitz Link

预先感谢!

angular angular-forms angular9 angular-formbuilder
1个回答
3
投票

您需要更改模板

将输入名称和ID设置为“ file-upload {{i}}”“,在ngFor内部,必须设置唯一的名称。可能有various bugs

example

// html
<div>
  <label for="file-upload{{i}}" class="custom-file-upload">
    <mat-icon class="icon">add_a_photo</mat-icon> Imagen del análisis
  </label>
  <input id="file-upload{{i}}" 
    name="file-upload{{i}}" type="file" 
    (change)="fileUploads($event, i);"
    accept="image/png,image/jpeg,image/jpg"/>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.