Angular 10在ngFOR中上载图像

Angular 10在ngFOR中上载图像,angular,image,upload,Angular,Image,Upload,在ngFOR中上载图像时如何更改img crs <div *ngFor="let product of products" > <input type='file' #fileInput (change)='onFileUpdate($event,product) style="display:none;'/> <img [src]='product.imgUrl' (click) = 'fileInput.click()'

在ngFOR中上载图像时如何更改img crs

<div *ngFor="let product of products"  >
  <input type='file' #fileInput (change)='onFileUpdate($event,product) style="display:none;'/>
  <img  [src]='product.imgUrl' (click) = 'fileInput.click()' />      
</div>

您可以执行以下操作

app.component.ts

import { Component } from "@angular/core";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  public products = [
    {
      id: 1,
      imgUrl: "",
      imgBase64Data: ""
    },
    {
      id: 2,
      imgUrl: "",
      imgBase64Data: ""
    },
    {
      id: 3,
      imgUrl: "",
      imgBase64Data: ""
    }
  ];

  onFileUpdate(event, index) {
    const files = event.target.files;
    if (files.length === 0) return;

    const reader = new FileReader();

    reader.readAsDataURL(files[0]);
    reader.onload = _event => {
      this.products[index].imgBase64Data = reader.result as string;
    };
  }
}
app.component.html

<div *ngFor="let product of products; let i = index">
  <input type='file' #fileInput (change)="onFileUpdate($event, i)" />
  <img *ngIf="product.imgBase64Data" [src]='product.imgBase64Data' (click) = 'fileInput.click()' width="100" height="100"/>
</div>

您可以上载图像并将其转换为Base64数据。然后您可以在UI上显示它。 如果必须在BE上保存图像,则也可以向BE发送base 64数据

你可以在这里查一下


如果您有任何疑问,请告诉我。

您是在BE上上载图像还是直接显示在UI上?当我在上载输入中选择图像时,我想更改src图像