Welcome to OverStack Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others


0 votes
in Technique[技术] by (71.8m points)

typescript - how can I change an image added dynamically in in angular

I have multiple input files dynamically added in angular. When I upload a file I want to change the only image of this input, but it is changing all the images of the input files. How can I fix that please.

images = [
      {url: 'assets/images/icons/ico_upload.svg'},
      {url: 'assets/images/icons/ico_cel.svg'}
    img = this.images[0];
    imgVisible = true;

    fileChangeEvent(event: any, keyName): void {
      this.imageChangedEvent[keyName] = event;

     if(event.target.files.length > 0) 
       this.img = this.images[1];
        this.img = this.images[0];        

html code:

<form [formGroup]="filterForm" class="filter-form" (ngSubmit)="Submit()">
                      <ng-container *ngFor="let item of questions2 ">

                          <div *ngSwitchCase="'file'"  >
                              <div class="file">
                                <span class=ellipsis matTooltip="{{item.des}}">{{item.des}}</span><br />
                                <img [src]="img.url">
                                  <input type="file" class="file-upload" (change)="fileChangeEvent($event,'sample')">

Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Since you are binding the image source the a single input

<img [src]="img.url">

All items in the list will be binded to the same image. I'll suggest to create a seperate array of images for each question, Or add new attribute for each item and the bind to item.imgUrl

<ng-container *ngFor="let item of questions2; let i = index">
<img [src]="item.imgUrl">
fileChangeEvent($event,'sample', i)

and in the component.ts

 fileChangeEvent(event: any, keyName, index): void {
 this.questions2[index].imgUrl = this.images[...];

Welcome to OverStack Developer Community-Open, Learning and Share