Can you showcase two distinct perspectives on a single page?

One of my components has nested ngFor directives looping through an array of users and their posts. I have a view link within this element, and when clicked, it should show detailed information about both the user and the post. However, the current setup is causing issues - the details shown are either incorrect or not corresponding to each other. The routing is set up with a route ending in :/ that displays both detailed views. Here's the code for the view link:

<a mat-button routerLinkActive [routerLink]="['/city-care/view-request/', request.id]">View</a>. 

I want to ensure that clicking on the view link will display the correct user and post details together. How can I achieve this? Any suggestions would be helpful.

Here's a snippet from my list component:

    <mat-accordion multi="true" *ngIf ="!isLoading && userIsAuthenticated">

  <h3>All User Requests</h3>

  <mat-expansion-panel class='panel' *ngFor="let user of users">
    <mat-expansion-panel-header *ngIf="user.requests.length > 0"> 
      <mat-panel-title>
        <p>Name:&nbsp; {{ user.first_name }}&nbsp;{{ user.last_name }}</p>
      </mat-panel-title>
    </mat-expansion-panel-header>
    <mat-panel-description  *ngFor="let request of user.requests">
      <p class='left-align'>Request: &nbsp;{{ request.name }} <br>
      {{request.details}}</p>
      <div class="col sm6 right-align">
        <a mat-button routerLinkActive [routerLink]="['/city-care/view-request/', request.id, 

    user.id]">View</a>
          </div>
        </mat-panel-description>
      </mat-expansion-panel>
    </mat-accordion>

And here's a glimpse of my detailed view component:

 <div *ngIf="request && user && !isLoading && userIsAuthenticated">
      <div class="card">
        Contact Person: {{user.first_name}} {{user.last_name}} <br>
      Email: &nbsp; {{ user.email }} <br>
      Phone: &nbsp; {{ user.phone }} <br>
      Mobile: &nbsp; {{ user.mobile_phone }} <br>
      <hr>
      Need: &nbsp; {{ request.name }} <br>
      Details: &nbsp; {{ request.details }}<br>
      Date Needed: &nbsp; {{ request.needByDate | date }} <br>
      </div>
    </div>
    <div class="col sm6 right-align">
      <button class="waves-effect waves-light btn back" routerLink="/city-care/site- 
      postings">Back</button>&nbsp;

    
    </div>

My current route looks like this:

{ path: 'city-care/view-request/:id', component: ViewRequestComponent, canActivate: [ AuthGuard 
 ] },

In the detailed view component ts file, I am using route snapshot to fetch the details. How can I ensure that both the user and the request details are displayed accurately on the same page?

Answer №1

It seems like a service is required to retrieve the user data in the detailed view component. Are you able to implement this?

In the ViewRequestComponent, you have the option to inject a dedicated service that has access to user information. Within the ngOnInit method, you can fetch the user associated with the request. You can refer to Angular's documentation for a similar example: https://angular.io/guide/router#accessing-query-parameters-and-fragments

ngOnInit() {
  const requestId = this.route.snapshot.paramMap.get('id')
  this.user = this.userService.getUserByRequestId(requestId)
}

Answer №2

It would be more efficient to organize the structure as follows:

  1. A HomeComponent
  2. A Component that displays a user information card
  3. A Component for showing a general post card
  4. A Component to display post details

In the HomeComponent, use *ngFor to render all users. For example, show 10 cards with each card displaying the user's firstName, LastName, and Avatar (route: http://localhost:4200/users). Clicking on a user's card will navigate to another component that uses *ngFor to display a list of all the user's posts. Show 10 cards where each shows the title of the posts (route: http://localhost:4200/users/12). Clicking on a post will render the details of that post (route: http://localhost:4200/users/12/13).

Your route configuration should look something like this:

export const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
  { path: 'users', component: UserComponent },
  { path: 'users/:id', component: PostComponent },
  { path: 'users/:id/:id2', component: PostDetailsComponent }
];

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

Utilize a variable within an HTML attribute

Currently utilizing Angular and I have the following HTML snippet <input onKeyDown="if(this.value.length==12 && event.keyCode!=8) return false;"/> Is there a way for me to incorporate the variable "myNum" instead of the ...

Express API is mistakenly including a "data" section in the response of all GET requests, something that was not intended

I'm currently developing a REST API and encountering an unexpected result when I send a /GET request. Upon making a GET request to the API, it is returning { data: { [{myExpectedObjects},{myExpectedObjects}] } } However, I am anticipating ...

What is the best way to combine data from two rows into one row?

Can someone help me with merging 2 sets of Line data into a single row for each entry? For example, the 'Green Bay Packers @ Chicago Bears' row should display '+3.5000 and -3.5000', while 'Atlanta @ Minnesota' should show &apo ...

Tips on transferring a child Interface to a parent class

Here is my code snippet: LocationController.ts import {GenericController} from './_genericController'; interface Response { id : number, code: string, name: string, type: string, long: number, lat: number } const fields ...

Dealing with Typescript in Node.js: Handling the error 'Property not found on type Global & typeof globalThis'

I recently encountered an issue with my NodeJS app that is built with typescript and global.d.ts file. The strange part is that everything works fine in my old application, but when I try to run the new one using ts-node-dev ts-main-file.ts, I encounter an ...

Creating a consolidated System.config mapping for @angular modules using a single .js file

Currently in the process of developing an Angular 2 application, with the specific requirement to consolidate all resulting Javascript files into a single .js file called output.js. Now, the challenge is to incorporate map configuration within System.conf ...

Tips for validating form input upon submission in Angular 6

Within my Angular application, I have successfully implemented form validators. However, I am aiming to trigger form validation specifically upon submission. This means that when the user clicks on the submit button and the form is invalid, the errors indi ...

How can I update a property within an object in a sequential manner, similar to taking turns in a game, using React.js?

I am currently working on a ReactJs project where I am creating a game, but I have encountered an issue. I need to alternate turns between players and generate a random number between 1 and 10 for each player, storing this random number inside their respec ...

Unable to successfully export ExpressJS routes to an external file when targeting the root path

I am seeking a way to organize my routes by exporting them into external files. Currently, all routes except the root route are functioning correctly: localhost/login -> "Login page" localhost/ -> empty server.js: // SERVER SETUP ============= v ...

Layout your Angular components with a column design using Flex Layout

Is there a way to adjust the width of a child component in an fxLayout set to column? Take this example for reference: https://stackblitz.com/edit/angular-fxlayout-custom-breakpoints?file=app%2Ftest.component.ts In the provided example, there are three f ...

What are the best scenarios for implementing modules, components, or standalone components in Angular 17?

Apologies if this question has been posed before, but I'm still navigating my way through Angular and could use some guidance on when to utilize modules, components, or stand-alone components. For instance, if I am constructing a modest website consi ...

What steps are involved in building a modal pop-up in Angular without using any pre-existing libraries

I am looking to create a modal popup when a button is clicked. I want to achieve this without relying on any additional dependencies. The method I have used below successfully creates a fully functional modal, but I am unsure if this is the best way to do ...

A guide to accessing a property value in Angular 6 from an object using a string key

In my Angular application, I am receiving an object with multiple arrays from a REST service. I need to access the value from the incoming object based on the property name. Here is what the object looks like: data{ array1:{}, array2:{}, array3:{} } Th ...

Warning: Obsolescence of Typescript Detected

Having an issue with my login code in TypeScript. The 'subscribe' function is deprecated and I'm not sure how to proceed. Can anyone provide some guidance? doLogin() { this.userService.doLogin(this.loginForm.value).subscribe( r ...

Why does my MEVN application only display the back end when I try to deploy it on Heroku?

I am encountering an issue with my app deployment on Heroku where the backend server is being displayed instead of my Vue app. Despite having an if statement in app.js that serves the files only in production, removing the if statement did not resolve the ...

What is the term used for the objects that res.render passes?

I constantly find myself struggling with defining objects inside res.render. Is there a way to define them globally or outside of res.render? I hope someone can offer some guidance.. here is a sample code snippet: router.get("/home/blog", function(req,r ...

Unusual error notification encountered in Node.js

Recently, I've been encountering a plethora of odd error messages, and now my app.js won't even start. I'm puzzled by the following error message - does anyone have any insight or solutions? node.js:201 throw e; // process.nextTick ...

Implementing dynamic search functionality with Knex

`let add_query = ".andWhere('company_name', 'like','%marker%')"; knex('franchisee').where('franchisee_name', 'like', '%jackmarker%')${add_query} .then((resp) => { console.log("res ...

Tips for creating a deepCss selector for an input Textbox in Protractor

When I attempt to use sendKeys in an input textbox with Protractor, the element is located within a shadow-root and there are three separate input textboxes. ...

Determine the implicit type of the assigned function, while also constraining the return type to be a subtype of a predefined

When writing multiple functions for server requests, I have encountered a dilemma with TypeScript. Each function must return a type that extends a specific predefined known type, but I also want TypeScript to infer the most accurate return type possible. ...