【问题标题】:Add title with each image before saving in Angular 6在 Angular 6 中保存之前为每个图像添加标题
【发布时间】:2019-05-15 18:36:53
【问题描述】:

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

<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>

在detectFiles中填充URL数组:

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

【问题讨论】:

  • 编辑您的问题,以便更清楚您想要做什么。如果您想要每个图像的标题,您应该在 ngFor 中有输入字段
  • 已编辑立即查看
  • 从@לבני מלכה查看下面的答案,应该是这样的。你需要它的模型,使用响应式或模板驱动的表单来验证字段

标签: javascript jquery html css angular


【解决方案1】:

创建包含titlefilemodel

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

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

Here is stackblitz example

【讨论】:

  • 感谢您的回答。如何单独创建 ts
  • 右键点击你的文件夹->添加文件->nameFile.ts
  • 然后将其导入您的组件中(参见 stackblitz 示例:stackblitz.com/edit/angular-7-master-1nysmt?file=src/app/…
  • 我正在选择多个文件并为每个文件指定标题
  • 你想要每个网址的标题吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-11-27
  • 1970-01-01
  • 2022-10-17
  • 1970-01-01
  • 1970-01-01
  • 2017-01-06
  • 1970-01-01
相关资源
最近更新 更多