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

Categories

0 votes
1.0k views
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) 
      {
        console.log(event.target.files[0].name);
       this.img = this.images[1];
  
      }else{
        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">
                                <label>
                                  <input type="file" class="file-upload" (change)="fileChangeEvent($event,'sample')">
                                </label>
                              </div>
                          </div>
 </ng-container>
              </form>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
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
...