如何使用* ngFor循环中的项目作为值?

时间:2019-11-22 15:24:51

标签: angular typescript ionic4

如何使用item.profile图片的值并在使用更新功能时使用它,如下面的代码所示?

<ion-content>
        <ion-grid style ="text-align: center">
         <ion-row class="ion-align-items-center" >
        <ion-col class="ion-align-items-center" *ngFor="let item of students" >
          <!--   <div  class= "imageHold" >
                <ion-img [src]= "profileImage || item.profileImage"></ion-img>
            </div> -->
            <ion-avatar class="ion-align-items-center">
                <ion-img [src] = "item.profileImage"></ion-img>
              </ion-avatar>
        </ion-col>  
       </ion-row>
         <ion-row  style ="text-align: center">  
           <ion-col>
             <ion-button  size="small" fill="outline" (click)="chooseProfilePic()" >Choose Profile Photo</ion-button>
           </ion-col>
        </ion-row>
       </ion-grid>

当我使用this.item.profileImage作为值时,为什么会在控制台中给我带来未定义的错误?

export class EditProfilePage implements OnInit {

  item: any

    this.profileImage =  "./assets/imgs/user.png" || this.item.profileImage;
    this.profileService.read_Students().subscribe(data => {

      this.students = data.map(e => {
        return {
          id: e.payload.doc.id,
          isEdit: false,
          userName: e.payload.doc.data()['userName'],
          userBio: e.payload.doc.data()['userBio'],
          profileImage: e.payload.doc.data()['profileImage'],
        };
      })
      console.log(this.students);


  UpdateRecord(recordRow) {
    let record = {};
    record['userName'] = recordRow.userName || "" ;
    record['profileImage'] = this.item.profileImage;
    record['userBio'] = recordRow.userBio || "" ;
    this.profileService.update_Student(recordRow.id, record);
    recordRow.isEdit = false;
  }

1 个答案:

答案 0 :(得分:1)

在循环中使用index,并在函数中通过index获取项目。在index函数中传递chooseProfilePic(i)

<ion-grid style="text-align: center">
    <ion-row class="ion-align-items-center">
        <ion-col class="ion-align-items-center" *ngFor="let item of students; let i = index">
            <ion-avatar class="ion-align-items-center">
                <ion-img [src]="item.profileImage"></ion-img>
            </ion-avatar>
        </ion-col>
    </ion-row>
    <ion-row style="text-align: center">
        <ion-col>
            <ion-button size="small" fill="outline" (click)="chooseProfilePic(i)">Choose Profile Photo</ion-button>
        </ion-col>
    </ion-row>
</ion-grid>

并按照逻辑获取项目:

chooseProfilePic(i) { 
  this.item = students[i]; // get item
  const profileImage = students[i].profileImage
}