erdemgunenc
erdemgunenc

Reputation: 997

*ngFor with multiple arrays

I have an object data which contains 2 arrays(photo and comments come from server) and I'd like to show them with *ngFor but ngFor shows only array types.

Here is my Ts file:

this.comments=[];
// ...
  .subscribe((data) => {
    this.comments= data.comments;
    console.log("data: ", data);
    this.commentPhoto = data.Photo; 
    // I don't want to create another array 
    // I want to make commentPhoto and comments array in 1 Array to show them.

HMTL

<ion-row *ngFor="let cm of comments">

  <ion-col col-2 style="border:1px solid grey;">
    <img src="{{cm.photo}}" style="width:45px;height:45px;">
  </ion-col>

  <ion-col col-10 style="border:1px solid grey;">
    {{cm}}
  </ion-col>
</ion-row>

How can I do it in 1 array data photo enter image description here Thank you.

Upvotes: 1

Views: 22685

Answers (4)

erdemgunenc
erdemgunenc

Reputation: 997

Thank you for your all answers, I solved it like this.

TS

 .subscribe((data) => {
  this.comments= data;

HTML

<ion-row *ngFor="let cm of comments.context; let i=index">

 <ion-col col-2 style="border:1px solid grey;">
  <img src="{{cm.photo[i]}}" style="width:45px;height:45px;">
 </ion-col>

<ion-col col-10 style="border:1px solid grey;">
    {{cm}}
 </ion-col>
</ion-row>

Here photo and context are the Arrays which are included in the data Ts file

Thank you for all.

Upvotes: 0

Avnesh Shakya
Avnesh Shakya

Reputation: 3906

I think you want to show both array from one *ngFor. I can see your data which are having two Arrays: comment and photo.

You can achieve it two ways, One is: Use index:

this.comments= data.comment;
this.commentPhoto = data.Photo;

Here if both array's length is same and order also, then try this:

<ion-row *ngFor="let cm of comments; let i = index">
  <ion-col col-2 style="border:1px solid grey;">
    <img src="{{commentPhoto[i]}}" style="width:45px;height:45px;">  // For photos
  </ion-col>
  <ion-col col-10 style="border:1px solid grey;">
    {{cm}}
  </ion-col>
</ion-row>

Second, Combined both array as object in one place before rendering in template:

data: [{comment: "...", photo: ""},..]

then render this. Hope this will work for you.

Upvotes: 8

monica
monica

Reputation: 1484

I do it this way:

/**
  * Function to return an array of keys of an object
  * @param itemObj
  * @returns {string[]}
 */
dataKeys(itemObj): Array<string> {
    return Object.keys(itemObj);
}
<ion-row *ngFor="let key of dataKeys">

  <ion-col col-2 style="border:1px solid grey;" *ngFor="let item of dataKeys[key]">
    <img src="{{item}}" style="width:45px;height:45px;">
  </ion-col>

</ion-row>

Upvotes: 0

PalamCoder
PalamCoder

Reputation: 70

I think you need to modify the result data. Make a model let's say PhotoData.

public class PhotoData
{
    public Image Photo { get; set; }
    public string Comment { get; set; }
}

And pass it to your TS file or service call.

Upvotes: 1

Related Questions