In Angular2, declaring variables with log={} and dynamically adding log details like [{id: "Logs List Details1"}, {id: "Logs List Details2"}] is a simple process

When declaring a variable with log = [{id: "Logs List Details1"},{id: "Logs List Details2"},....etc}] dynamically, issues arise when pushing dynamic data to it. If the data is static and pushed incrementally, it exceeds the page limit. However, if only one static value is passed for the log object and data is appended to it, only one value is displayed without pagination. This means that dynamic data is not being properly appended Here, the page limit per page is set at 3.

********here is my modified HTML code************

    <div class=" list-servers">
      <div class="col-md-12">
        <span>Default Log</span>
        <span class="flt-right"><a href="#"><img src="images/plus.png">==</a>
        </span>
      </div>
    </div>

    <div class="container">
      <div class="row" id="row-main">
      <div class="row">

       </div>
       <div class="col-md-9" id="content">

         <div class="content-area">
           <ng2-smart-table *ngIf="log" [settings]="settings" [source]="log" 
                  [defaultSettings]="defaultSettings" >
           </ng2-smart-table>
         </div>
        </div>
      </div>
    </div>

**************And here is my revamped .ts file***************
***********I am utilizing Ng2-smart-table to present my log details.***********

    import { Component, OnInit, OnChanges } from '@angular/core';
    import any = jasmine.any;
    import {GetDefaultLogService} from '../get-default-log.service';
    import {DefaultLogItem} from '../default-log-item';
    import { OauthTokenService } from '../oauth-token.service';


    @Component({
     templateUrl: './get-default-log.component.html',
     styleUrls: ['./get-default-log.component.css']
    })
    export class GetDefaultLogComponent implements OnInit{

     defaultLogItemValue: string;
     servername = sessionStorage.getItem("servername");
     logType = sessionStorage.getItem("logType");
     hidediv: boolean = true;

     settings = {
     columns: {
      id: {
        title: 'Logs List Details'
      }
     }
     };

    protected defaultSettings: Object  = {
      mode: 'inline', // inline|external|click-to-edit
      hideHeader: false,
      hideSubHeader: true,
      attr: {
        id: '',
      },
      noDataMessage: 'No data found',
      columns: {},
      pager: {
        display: true,
        perPage: 10
      }
    };

      defaultLogItems: DefaultLogItem[];

      // log:Array<any>=[{id: ""}];
      //log:any=[];
      //I want json in this format dynamically
      log=[
       {id: "Logs List Details1"},
       {id: "Logs List Details2"},
       {id: "Logs List Details3"},
       {id: "Logs List Details4"},
       {id: "Logs List Details5"}
      ];


  constructor(private service: GetDefaultLogService, private oauthTokenService: 
    OauthTokenService) {
        this.service.getLogItemList(this.oauthTokenService.getHeaders(), 
        sessionStorage.getItem("server"), 12345, 
        sessionStorage.getItem("startDate"), sessionStorage.getItem("endDate"), 
        sessionStorage.getItem("logType")).subscribe(lst =>{
          this.defaultLogItems = lst;
          for(var v in lst[0].logList) {
            this.log.push({id: lst[0].logList[v]});
          }

        });
    }

      ngOnInit() {
        console.log("this.defaultLogItems"+this.log);
      }
    }

********Please provide suggestions on how to achieve pagination while avoiding static data. The desired page limit is 10.

How can I declare the log variable as an array of objects with IDs like "Logs List Details1", "Logs List Details2", etc., dynamically? Static input results in exceeding the page limit when dynamic data is added. Conversely, passing only one static value and appending data leads to single value display without pagination. Dynamic data fails to append directly in this scenario.

Answer №1

To form an array in a specific structure:

logsArray=[ 
    {key: "Logs List Item 1"}, 
    {key: "Logs List Item 2"}, 
    {key: "Logs List Item 3"}, 
    {key: "Logs List Item 4"}, 
    {key: "Logs List Item 5"}

];

Give this a try

var logsArray= [];
for (let j = 1; j <= 100; j++) {
  let logItem = {
   key:j
};
logsArray.push(logItem);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When building with Angular using the "ng build" command, the JavaScript file names are altered

I'm currently learning Angular and I've noticed that when creating a new project with Angular CLI, files like runtime.js, polyfills.js, main.js, styles.css are generated. However, after running the ng build command, similar files can be found in ...

How can we transform the `toUSD(amount)` function into a prototype function?

This function is functioning perfectly as intended. function toUSD(amount): string { // CONVERT number to $0.00 format return new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(amount); }; Here is how I currently i ...

Retrieve all items that match the ids in the array from the database

I'm having trouble receiving a list of items that match with my array of ids. Here's a snippet from the Angular component code: this.orderService.getSpecyficOrders(ids) .subscribe(orders => { ... Where ids is an array of [{_id : ID }, ...

Express functions properly when handling the root route, but encounters issues with sub routes as it sends empty response bodies

Inside the routes.ts file: const router:Router = express.Router() // Route to get all blogs router.get('/',async (req:Request,res:Response)=>{ res.status(200).send("message sent") }) router.get('/admin',async (req:Requ ...

Instructions for accessing the side menu upon navigating to a new page

I'm working on an Ionic4 app that integrates with Google Firestore and includes a login feature. My goal is to have the sidemenu automatically open whenever a user logs into the application. For example: Login > PageX > *Open Sidemenu. How can ...

Struggling to integrate the Animejs library into my TypeScript and webpack project

Transitioning from ES5 to TypeScript and webpack, I decided to incorporate the Three.js library seamlessly. Alongside this, I wanted to utilize the Anime.js library for its impressive timeline animation features. However, my efforts yesterday were fraught ...

The specified control name formControlName in the Angular reactive form cannot be located

Having encountered this issue multiple times on Stack Overflow without any success, I am reaching out for help to identify what I might be doing wrong. In my component : ngOnInit() { this.companyCreatForm = this._formBuilder.group({ name: [null, ...

Angular 2 FormArray validation based on conditions

My goal is to apply validation rules based on changes in one field to another field within a formGroup that is nested inside a FormArray containing multiple instances of this group. Specifically, when the date field is modified, I need the Reason for Chang ...

Configuration options for Path Aliases in TypeScript

In my Next.js project, I am utilizing TypeScript and have organized my files as follows: |-- tsconfig.json |-- components/ |---- Footer/ |------ Footer.tsx |------ Footer.module.sass My path aliases are defined as:     "paths": {       ...

Update the image source dynamically upon the opening of an accordion in Angular

I have the following HTML code snippet in my file: <div class="col-md-3 col-sm-2 col-2 collapsedData" > <a class="collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" aria-expanded="false" aria-con ...

The function in Angular 5/Typescript disappears when attempting to call it from within another function

After importing D3 into my component, I encounter an issue when trying to assign a layout to the D3.layout property. Strangely, although the layout property is present in the console output of my D3 object, it seems to be unknown when I attempt to call i ...

The specified 'Object' type does not match the required 'Document' constraint

I need assistance with running a MERN application to check for any issues, but I keep encountering this error across multiple files. Error: The 'CatalogType' type does not meet the requirements of 'Document'. The 'CatalogType&apo ...

In Typescript 2.2, when using Express, the request and response objects are implicitly

I'm facing some challenges when it comes to incorporating types into my node/express project. Currently, I am using TypeScript 2.2 and express 4.x with the following npm installation for types: npm install --save-dev @types/express import * as expr ...

Translating from a higher-level programming language to a lower-level programming language

Is compilation effectively the transformation of high-level programming languages (HLL) into machine code or low-level language? If so, why is TypeScript (a HLL) compiled to JavaScript (also a HLL) instead of being compiled to a low-level language? ...

latest version of PrimeNG dropdown is 16.2

I am inquiring about how to implement virtual scrolling in a dropdown menu and connect the virtual scroll with an API backend. Specifically, I would like to know how to trigger an API call when the user reaches the end of the scroll, incrementing the page ...

Perform simple arithmetic operations between a number and a string using Angular within an HTML context

I'm stuck trying to find a straightforward solution to this problem. The array of objects I have contains two values: team.seed: number, team.placement: string In the team.placement, there are simple strings like 7 to indicate 7th place or something ...

I was able to use the formGroup without any issues before, but now I'm encountering an error

<div class="col-md-4"> <form [formGroup]="uploadForm" (ngSubmit)="onSubmit(uploadForm.organization)"> <fieldset class="form-group"> <label class="control-label" for="email"> <h6 class="text-s ...

Merging two arrays concurrently in Angular 7

When attempting to merge two arrays side by side, I followed the procedure below but encountered the following error: Cannot set Property "account" of undefined. This is the code in question: acs = [ { "account": "Cash In Hand", ...

Add a new module to your project without having to rely on the initial

I'm looking to experiment with a module by making some adjustments for testing purposes. You can find the code here. Currently, all I need to do is type "npm install angular2-grid" in my terminal to add it to my project. Here's my concern: If ...

What is the best way to set HTML content in the ElementRef's nativeElement?

I am trying to use a directive to set the content of an HTML element. export class AdvertisementDirective { constructor(el: ElementRef) { el.nativeElement.style.background = 'yellow'; el.nativeElement.content = '<p>Hello Wo ...