Showing information from a JSON dataset of users once a specific User ID has been chosen

My task involves displaying user data from an array and then showing the details of the selected user. I attempted to achieve this with the following code:


users = USERS; // contains data
selectedUser: User;

constructor() { }

ngOnInit() {
}

onSelect(index): void {
this.selectedUser = index;
}

Here is a snippet from my HTML file that I used:

      
    <div class="row">
        <div class="col-4">
          <ul class="menu">
            <div *ngFor="let user of users; let i = index"
              (click)="onSelect(i)">
              <span><b>{{user.id}}</b></span> {{user.name}}
            </div>
          </ul>
        </div>

        <div *ngIf="selectedUser" class="col-8 menu">
          <div><span><b>id: </b></span> {{selectedUser.id}} </div>
          <div><span><b>Name:</b></span> {{selectedUser.name}} </div>
          <div><span><b>Location:</b></span> {{selectedUser.location}} </div> 
        </div>
     </div>

I need help figuring out the correct condition to use in the ngIf directive for displaying the data.

Answer №1

Here is the correct code snippet:

onSelect(index): void {
   this.selectedUser = this.users[index];
}

The previous code was assigning only the index, leading to an incorrect attempt at fetching data from that variable. By using the above code, relevant data from the users array will be assigned and displayed in your UI.

Answer №2

In order to access all the details of the selected user, you need to store the index of the user in the selectedUser variable.

Here is the current behavior:

onSelect(index): void {
    this.selectedUser = index; //The index can be any number
}

If the index is 4 and this.selectedUser=4, then {{selectedUser.id}} will be undefined, which is why nothing is displayed.

To retrieve all data of the selected user, it is necessary to save the user in the this.selectedUser variable like this:

<div class="row">
   <div class="col-4">
      <ul class="menu">
        <div *ngFor="let user of users; let i = index"
          (click)="onSelect(user)">
        </div>
      </ul>
    </div>

onSelect(user): void {
    this.selectedUser = user; // user is the current user
}

Alternatively, instead of the current code, you can store the user with an index like so:

onSelect(index): void {
   this.selectedUser = this.users[index];
}

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

Restrict the parameter type using a type predicate

How can I effectively narrow types based on the value of a single field in TypeScript? It seems that using type predicates may not be working as expected to narrow down the types of other parameters within a type. Is there a way to ensure correct type na ...

Internal variable via router

The Back button on my main component is not always visible, depending on the child component. I have attempted to use a local variable with no success. In my parent app.component.html file, I have included the following: <button *ngIf="child.goBackUrl ...

Tips for creating a custom script in my React Native application

My React Native app requires a script to generate static files during the release process. The app is a game that utilizes pre-computed boards, which are resource-intensive to compute. Therefore, I am developing a script that will create these boards and s ...

There seems to be a syntax error in the regular expression used in Angular TypeScript

I've encountered an error and I'm struggling to identify the syntax issue. core.mjs:6495 ERROR SyntaxError: Invalid regular expression: /https://graph.microsoft.com/v1.0/communications/callRecords/getPstnCalls(fromDateTime=2020-01-30,toDateTime ...

React type-script does not trigger the onClick event for CheckBox

I have created a custom component called MyCheckBox (which I am using as a helper component). I imported this component into another one, but for some reason, the event is not being triggered when I try to click on it. Here is the code for reference: MyC ...

Combining Angular subscriptions to fetch multiple data streams

I am looking to retrieve the most recent subscription from a group of subscriptions. Whenever the value of my FormControl changes, I want to capture only the latest value after the user has finished typing. Below is the code snippet I am using - let cont ...

Guide on transferring the token and user information from the backend to the front-end

Here is the code from my userservice.ts file export class UserService { BASE_URL = "http://localhost:8082"; constructor(private httpClient:HttpClient) {} public login(loginData:any){ return this.httpClient.post(this.BASE_URL+"/au ...

Navigating back to the starting point

I'm experiencing an issue while trying to navigate using the Router.navigate method. Despite following all instructions meticulously, whenever I attempt to route via API, it reloads the root page. Within my RootComponent implementation, I am utilizin ...

Having difficulty with installing the ttf-loader for React with Typescript

Currently, I am working on a project using React with TypeScript and trying to incorporate the font feature in react-pdf/renderer. The font has been successfully imported and registered as shown below: import { Text, View, StyleSheet, Font } from "@re ...

Using the useContext hook across multiple files without needing to export it

I am working on a React app that has multiple states being managed function App(){ const [activeChoice, setActiveChoice] = useState("flights"); const [overlay, setOverlay] = useState(false); const [airports, setAirports] = useState([]); const [loading, ...

Checking for String Const Type in TypeScript

In my code, I have a custom type called Admin with two possible values: 'ADMIN' or 'AGENT'. There is a function that retrieves the user role from local storage: return localStorage.getItem('role'); I am looking to verify if ...

What is the best method for incorporating a delay within the upcoming subscribe block in Angular?

When subscribing to a service method, I have a sequence of actions that need to occur: displaying a toaster, resetting a form, and navigating to another component. However, I want to introduce a delay before the navigation so users can see the toaster mess ...

Optimal techniques for Angular 2 and beyond

When creating a CRUD for an entity using a REST API, what is the recommended best practice for updating data? On the main screen where there is a list of elements and a new element is added through a modal, should the list be updated locally or by callin ...

Express string declaration in a single TypeScript line

const restrictString = (str: string): string => str.match(/[ab]/g)?.join('') || '' Is there a way to restrict a string to only contain the characters 'a' and 'b' in a one-liner function? I am aware that this can ...

Encountering an issue with multi ./src/styles.scss during the deployment of my Angular application on Heroku

My attempt to deploy my Angular app on Heroku is resulting in an unusual error. I've experimented with changing the styles path in angular.json, but it hasn't resolved the issue. I suspect it's a path problem, yet I can't seem to corre ...

Exploring the implementation of float type in TypeScript

Is it possible to use Number, or is there a more type-specific alternative? In the past, I have relied on Number and it has proven effective for me. For example, when defining a variable like percent:Number = 1.01... ...

Firebase and Nx: Encountering issues with running emulators

I've been attempting to launch the Firebase emulators within the Nx workspace. Initially, I added firebase to my project: npm install firebase @angular/fire --save nx g @angular/fire:ng-add // configures the package in the project (unsuccessful) ng ...

TSLint has detected an error: the name 'Observable' has been shadowed

When I run tslint, I am encountering an error that was not present before. It reads as follows: ERROR: C:/...path..to../observable-debug-operator.ts[27, 13]: Shadowed name: 'Observable' I recently implemented a debug operator to my Observable b ...

The names of properties in Typescript are determined by the values of the outer type properties

In my project, I have various interfaces (or types) defined as follows: export type simpleValue = string | number | boolean | Date | null; export interface Options { inline?: OptionsItem[] | unknown[]; promptField?: string; selectedValues?: unknown[ ...

The keys within a TypeScript partial object are defined with strict typing

Currently, I am utilizing Mui components along with TypeScript for creating a helper function that can generate extended variants. import { ButtonProps, ButtonPropsSizeOverrides } from "@mui/material"; declare module "@mui/material/Button&q ...