Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k 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 Reply

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[...];


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...