在保存到Angular 6中之前,为每个图像添加标题

时间:2019-05-15 09:27:24

标签: javascript jquery html css angular

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

enter image description here

<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);
      }
    }
  }
}

1 个答案:

答案 0 :(得分:3)

创建包含modeltitle

file

FileUploadModel.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" />

我在RFC存储库中创建了要上传的文件,您可以看看

github