首页 > 解决方案 > 在 Angular 6 中保存之前为每个图像添加标题

问题描述

我正在使用以下代码显示多个图像的预览,现在我必须为每个图像添加标题然后我必须保存。

在此处输入图像描述

<input class="form-control" id="uploadimg" type="file" name="fileupload1" (change)="detectFiles($event,'gallery')" multiple>

<ng-container *ngFor="let url of urls;let n = index;">
  <div class="gallery-close">

    <div class="row-field">
      <h4>Title</h4>
      <input class="field-200" name="gal_title" size="25" />
    </div>
    <img [src]="url" name="url" class="rounded mb-3" width="100" height="100">
    <i class="fa fa-times" aria-hidden="true"></i>
  </div>
</ng-container>

URL 数组填充到 detectFiles 中:

export class AppComponent {

  urls = new Array<string>();

  detectFiles(event) {
    this.urls = [];
    let files = event.target.files;
    if (files) {
      for (let file of files) {
        let reader = new FileReader();
        reader.onload = (e: any) => {
          this.urls.push(e.target.result);
        }
        reader.readAsDataURL(file);
      }
    }
  }
}

标签: javascriptjqueryhtmlcssangular

解决方案


创建model包含titlefile

文件上传模型.ts

export class FileUploadModel{
file: File;
title: string;
}

在您的组件中使用

export class AppComponent  {
  urls = new Array<string>();
  list: Array<FileUploadModel>=[];
  title:string;

  detectFiles(event) {
    this.urls = [];
    let files = event.target.files;
    if (files) {
      for (let file of files) {
        let reader = new FileReader();
        reader.onload = (e: any) => {
          this.urls.push(e.target.result);
        }
        reader.readAsDataURL(file);
        //push the file list and title to list of model
        this.list.push({ file: file, title: '' });
      }
    }
  }
  save(){
    console.log(this.list)
  }
}

在 html 中添加ngModel到标题

 <input [(ngModel)]="list[n].title" class="field-200" name="gal_title" size="25" />

我在我的github存储库中创建了上传文件你可以看看

这是stackblitz示例


推荐阅读