Navigating through objects using a click event in Angular/ TypeScript

When I receive data from a Web API, my component includes two methods: one to load the next record and another to load the previous record. The goal is to click on an iteration of object data and display it.

Custom Component

export class NewResponseComponent implements OnInit {


 private view: BehaviorSubject<ConsulationResponsesIdListDataModel>;
 private responseCurrentState: ResponseCurrentStateDataModel;
 private responses: ConsulationResponsesIdListDataModel;

 private responseData = false;

     constructor(private dataService: ConsultationResponsesListDataService,
  private router: Router,
  private session: SessionStorageService){}

ngOnInit(): void {
  this.view = new BehaviorSubject<ConsulationResponsesIdListDataModel>(null);    
   this.loadData();
}

public loadData():void
{

  this.dataService.getConsultationResponsesList(this.responseCurrentState.consultationId, this.responseCurrentState.responseTypeId, this.responseCurrentState.responsesRequestedStatus)
     .subscribe(data =>{
          this.view.next(data);
          this.responses = data;
          this.responseData = true; 
     });
}

public loadNextResponse():void
{
    console.log("request for next response");
}


public loadPreviousResponse():void
{
  console.log("request for previous response");
}

The template below shows all the data in the response object, but the intention is to link it with the loadNextResponse() and loadPreviousResponse() methods in the above component.

Template

<div *ngIf='responseData'>
<div *ngFor="let response of responses" class="form-row">
   {{response.responseId}}
</div>

<button class="btn btn-default width-50 mb-xs" (click)="loadNextResponse()">Load Next Response</button>
<button class="btn btn-default width-50 mb-xs" (click)="loadPreviousResponse()">Load Previous Response</button>

I am aiming for functionality similar to the example found here: http://jsfiddle.net/h2G64/

Answer №1

Here is a possible solution to your issue:

<div>
    <!-- <div *ngFor="let response of responses" class="form-row">
        {{response.responseId}}
    </div> -->
    {{responseItem}}
    <button [disabled]="!count || count <= 0" class="btn btn-default width-50 mb-xs" (click)=" count = count - 1; responseItem = responses[count]">Load Previous Response</button>
    <button [disabled]="!!count && count >= responses?.length - 1" class="btn btn-default width-50 mb-xs" (click)="count = count || 0; count = count + 1; responseItem = responses[count]">Load Next Response</button>
</div>

Remember to set the initial value of responseItem when fetching the first response from the server for the navigation to work.

UPDATE - Attached GIF of Proof of Concept

Take a look at this GIF demonstrating my proof of concept -

https://i.sstatic.net/z0BIm.gif

If you have any other questions, feel free to ask.

I hope this explanation helps :)

Answer №2

Here is the solution I came up with:

Custom Component Logic

export class NewResponseComponent implements OnInit {

   private nums:number[] = [0,1,2,3,4,5,6,7,8,9];
   private currentResponseIndex=0;
   private currentResponse;

 public loadNextResponse(responseIndex: string):void
{

    this.currentResponseIndex = parseInt(responseIndex)+1;

    if(this.nums[this.currentResponseIndex]!=null)
    {
      this.currentResponse = this.nums[this.currentResponseIndex];
      console.log("response index  ",this.currentResponseIndex, "    response ", this.currentResponse);
    }
    else
    {
      this.currentResponseIndex = this.currentResponseIndex-1;
      console.log("reach to max length ", this.currentResponseIndex);
    }

}


public loadPreviousResponse(responseIndex: string):void
{

  this.currentResponseIndex = parseInt(responseIndex) - 1;
  if(this.currentResponseIndex<0)
  {
    this.currentResponseIndex = 0;
    console.log("reach to min length");
  }
  else
  {
    this.currentResponse = this.nums[this.currentResponseIndex];
    console.log("response index  ",this.currentResponseIndex, "    response ", this.currentResponse);
  }
}

Custom Template Design

<div>
    <h1><span>Current Response Index </span>{{currentResponseIndex}}</h1>
    <h1><span>Current Response  </span>{{currentResponse}}</h1>

    <button class="btn btn-default width-50 mb-xs" id = "{{currentResponseIndex}}" (click)="loadNextResponse(currentResponseIndex)">Load Next Response</button>
    <button class="btn btn-default width-50 mb-xs" id = "{{currentResponseIndex}}" (click)="loadPreviousResponse(currentResponseIndex)">Load Previous Response</button>
</div>  

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

Can you provide instructions on how to display data in two lines within a mat-select field?

Is it possible to show selected options in mat-select with long strings in two lines within the same dropdown? Currently, the string appears incomplete. You can see an example of this issue here: incomplete string example <mat-form-field class="f ...

Managing Autocomplete Functionality in React with Material-UI, Both with and without a Pre

I am in need of an Autocomplete feature that offers the following functionalities: If the initial value has an id greater than 0, then I want the autocomplete to default to the provided object. If the initial value has an id less than or equal to 0, then ...

Utilize the datasource.filter method within an *ngFor loop

I have a table that filters based on certain search criteria, which I implemented using the example found at: https://material.angular.io/components/table/examples Now, I am wondering if it is possible to apply this filtering functionality to an *ngFor lo ...

Ensuring there are no null values in TypeScript

I am encountering an issue with the following TypeScript code: console.log ('collection[0] -> ' + collection[0] ); console.log ('collection[0] !== null -> ' + collection[0] !== null); However, the output on the console is unexp ...

Angular2 does not load Js twice

I specified the path to my JS file in angular.cli. It loaded successfully during the initialization of the Angular app, but when navigating back to the component, it failed to load. Any suggestions on how to fix this issue would be greatly appreciated. Th ...

Using a dropdown list to filter values in a table with Angular ngBootstrap

Seeking assistance with filtering table values based on the selected filter. I plan to utilize this ngbDropdown as my filter. If I choose company A, only entries related to company A will be displayed in the table. I am unsure about how to connect the f ...

What is the process for integrating GraphQL resolvers in Typescript using Graphql-codegen?

With the goal of learning Apollo Server, I decided to implement the schema outlined here. The CodeGen produced what seemed to be logical type definitions for books and libraries. export type Book = { __typename?: 'Book'; author: Author; tit ...

JavaScript method of retrieving an object inside an array nested within another object via multer

Below is my custom multer function to handle file uploads - const storage = multer.diskStorage({ destination: (req, file, callback) => { let type = req.params.type; let path = `./data/${type}`; fs.mkdirsSync(path); callback(null, path) ...

Monitor data changes by utilizing observables in Angular

At the start, I have a boolean variable named loading which is set to false, and there's a button whose text is determined by the value of this variable. To handle this functionality, I created a method as follows: changeBtnTxt() { this.loginBtn = ...

When working with Angular 12, the target environment lacks support for dynamic import() syntax. Therefore, utilizing external type 'module' within a script is not feasible

My current issue involves using dynamic import code to bring in a js library during runtime: export class AuthService { constructor() { import('https://apis.google.com/js/platform.js').then(result => { console.log(resul ...

Generate dynamic rows with auto-generated IDs on click event in Angular

Can anyone assist me in dynamically adding rows and automatically generating IDs? I am currently using a click event for this task, but when adding a row, I have to input details manually. Is there a way to automate this process? Any help would be greatly ...

Issue: Using the command 'typings search' successfully locates a package, however, when attempting to install it using 'typings install', the process fails

I am currently attempting to install the Google Auth2 typings using 'typings': > typings search gapi.auth2 This command returns: NAME SOURCE HOMEPAGE DESCRIPTION VERSIONS UPDATED gapi.auth2 d ...

How can we efficiently load paginated data from a database while still implementing pagination using Angular Material?

I have a large table with more than 1000 entries that I want to display using a <mat-table></mat-table>. Since loading all the entries at once would be too much, I am looking to implement pagination and load only 20 entries per page. The chal ...

Exploring the use of @HostListener in Angular for handling drop events

I am currently working on developing a directive for drag and drop functionality with files. I have successfully implemented the dragenter and dragleave events, but for some reason, the drop event is not being recognized. @HostListener('drop', [ ...

Applying background color within an *ngFor loop

My question may not be perfectly described by the title, but here it is. In my Angular Material2 project, I have an md-toolbar where I am dynamically looping through values: <md-toolbar (click)="selectedToolbarValue(key.Name)" *ngFor="let key of array ...

Is there a way to configure Angular CLI to enable loading a favicon with a content hash for its filename?

I am looking to cache my website's favicon in the same way I cache css, js, and png files by setting an expires header far into the future. However, I am struggling to figure out how to achieve this. Most resources I come across suggest using a link i ...

What are the differences between using `common/esm5/http` and `http/esm5/http`?

I have come across two HTTP packages in the latest version of Angular where webpack is detecting 2 different versions/sources. Upon investigating, I discovered that they are coming from different locations: @angular/common/esm5/http.ja @angular/http/esm ...

How can I capture the logs from Sentry and send them to my own custom backend system?

I successfully implemented Sentry in my Angular Application. Is there a method to retrieve logs from Sentry and transfer them to a custom endpoint? I aim to integrate the Sentry Dashboard with my backend (developed using Java Springboot). Appreciate the ...

Developing a system that combines REST API and Socket.io to handle user permissions and send out notifications

Currently, I am working on building a restful API in node.js/express to perform standard CRUD operations. In addition to this, I want to be able to notify clients of any Create/Update/Delete events that occur using either ws or socket.io for simplicity. I ...

Unleashed Breakpoint Mystery in Ionic 5 Angular with VSCode

I recently upgraded my Ionic 5 Angular 12 app from Ionic 4 Angular 8. The application is working well and remains stable, but I have encountered some issues while debugging. Firstly, when I use the launch.json file in Visual Studio Code to run the app, it ...