Display array as paginated views

Viewed 154

I am trying to display an array of objects as Angular PPT view pages using ngFor. To do that, I have prepared a temporary object and it is working fine and I am able to display it as pages.

temporary object:

let data = [
      {
        "page": "page1",
        "data": [
          {
            "id": "1",
            "content": "abc",
            "checked": true
          },
          {
            "id": "2",
            "content": "xyz",
            "checked": true
          }
        ]
      },
      {
        "page": "page2",
        "data": [
          {
            "id": "3",
            "content": "abc",
            "checked": true
          },
          {
            "id": "4",
            "content": "xyz",
            "checked": true
          }
        ]
      }
    ]

However, with my original array I am not able to convert to the same format

original array

[
  {
    "id": 1,
    "content": "abc"
  },
   {
    "id": 2,
    "content": "xyz"
  },
   {
    "id": 3,
    "content": "xyz"
  },
   {
    "id": 4,
    "content": "xyz"
  }
]

Based on content length I have to create page numbers and show the objects in html using ngfor, e.g. If object1 and object2 length is more than 1000 than i have to display only object1 which length is less than 1000 in page1 and object2 in page2, I have tried to convert it based on content length but i have stuck on this.

what I tried so far:

this.templateArray.map((item) => {
      var a = item.content.length;
      this.totallength = this.totallength + a;
      if (this.totallength >= 500) {

        this.totallength = [];
      }
      dataobj = [{
        "page": pageNo,
        "data": [
          {
            "content": item.content
          }
        ]
      }];
      temp.push(dataobj);
    })

Any help will be great...

1 Answers

You can try something like this:

Working Demo

  constructor() {
    var newPageContentLength = 0;
    var pageNo = 1;
    var pageObj = {
      page: `page${pageNo}`,
      data: []
    };

    this.originalArray.forEach((item, i) => {
      newPageContentLength += item.content.length;
      if (i == 0) {
        pageObj.data.push({ ...item, checked: true });
      } else {
        if (newPageContentLength < 20) {
          pageObj.data.push({ ...item, checked: true });
        } else {
          this.viewArray.push({ ...pageObj });
          pageNo += 1;
          pageObj = {
            page: `page${pageNo}`,
            data: [{ ...item, checked: true }]
          };
          newPageContentLength = item.content.length;
        }
      }
      if (i == this.originalArray.length - 1) {
          this.viewArray.push({ ...pageObj });
      }
    });
  }

Note: This is just an example with max content length of a page being 20. You can modify/refactor the function as required

Related