Retrieving a specific user attribute from the database using Angular

Currently, I am working on developing an application that utilizes ASP.NET for the Back End (API) and Angular for the Front End of the application.

Within the API, I have set up controllers to retrieve either a list of users from the database or a single user.

    [HttpGet]
    public async Task<ActionResult<IEnumerable<User>>> Get()
    {
        return await _dbContext.Users.ToListAsync();
    }

    [HttpGet("{id}")]
    public async Task<ActionResult<User>> GetUser(int id)
    {
        return await _dbContext.Users.FindAsync(id);
    }

On the Angular side, I have added the following code snippet to the component's .ts file:

export class Component1 implements OnInit {
    users: any;

    constructor(private http: HttpClient) { }
    
    ngOnInit(): void {
        this.getUsersList();
    }
    
    getUsersList() {
        this.http.get('https://localhost:44357/api/').subscribe(response =>
        {
          this.users = response;
        }, error => {
        console.log(error);
        })
  }

Furthermore, in the component's .html file, I have included the following code to display a list of all user names from the database:

<div class="d-flex justify-content-center">
        <select class="form-select">
                <option *ngFor ="let user of users">{{user.name}}</option>
        </select>
</div>

Currently, my challenge lies in returning a specific property (such as the name property) of a single user in another component.

Below is the .html file for that component:

<div class="d-flex justify-content-center">
    <form>  
        <input class = "textbox" type="text" name="Name" value="0"> 
    </form>
</div> 

And here is the .ts file for the same component:

export class Component2 implements OnInit {

  user: any;

  constructor(private http: HttpClient) { }

  ngOnInit(): void {
    this.getUser();
  }

  getUser() {
     this.http.get('https://localhost:44357/api/{id}').subscribe(response =>
     {
       this.user = response;
     }, error => {
       console.log(error);
     })
   }
}

I am looking for a solution to display the property of a single user (stored in the database) in the textbox. Any suggestions on how I can achieve this?

Answer №1

Ensure that you include the ngModel directive in your input control:

<div class="d-flex justify-content-center">
    <form>  
        <input class = "textbox" type="text" [(ngModel)]="user.name" name="name"> 
    </form>
</div>

Don't forget to inject FormsModule into your AppModule class as well:

import { FormsModule } from '@angular/forms';

@NgModule({
  imports: [
    ...
    FormsModule
  ],
  declarations: [
    ...
  ],
  providers: [],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

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

What are some solutions to the "t provider not found" error?

Upon deploying my application on the production server using GitLab/Docker, I encountered the following error message: ERROR Error: No provider for t! at C (vendor.32b03a44e7dc21762830.bundle.js:1) at k (vendor.32b03a44e7dc21762830.bundle.js:1) at t._thr ...

Guidelines for Extracting TextBox Value from GridView

In my gridview, I have dynamically created TextBox controls in the RowDataBound event: TextBox txtbox = new TextBox(); txtbox.ID = "txt1"; txtControl.Text = "SomeValue"; However, when attempting to retrieve the value on a button click using the following ...

What is the reason behind the term "interpolation" for the double curly braces in Angular/

Even after over a year of experience with Angular/JS, I find myself struggling to truly grasp the concept of interpolation (for example, {{1+4}}). Can you explain the origin of this term in the context of Angular/JS and if it shares any similarities with ...

Error message: The class heritage events_1.EventEmitter is invalid and cannot be recognized

There seems to be a problem with the [email protected] npm dependency. I am attempting to incorporate mongodb into my Vue.js + Vite + Typescript application, but it crashes and fails to load due to an error originating from mongodb. It appears that th ...

When restarting nginx, Angular fails to display the index page

On my VPS server, I have an application with the backend coded in node.js and the frontend in Angular. After restarting nginx, I encountered some issues where my API stopped working on HTTPS and only functioned on HTTP (previously, I was able to make requ ...

What is the reason for my algorithm's inability to work with this specific number?

I'm currently working on creating an algorithm to compute the sum of prime numbers that are less than or equal to a specified number. Below is my attempt: function calculatePrimeSum(num) { // initialize an array with numbers up to the given num let ...

Issue with handling http errors and navigating routes in Angular 2

Whenever I check a user's token authentication and encounter a 401 error, I aim to redirect them to the login page. The issue arises when attempting to navigate to the login page within the error catch block. constructor(private http: Http , private ...

Issue: Formcontrolname attribute is undefined causing TypeError when trying to retrieve 'get' property.Remember to define formcontrolname attribute to

Having trouble creating a form at the moment and keep encountering this error: 'ERROR TypeError: Cannot read property 'get' of undefined' Even after trying various solutions like using formControlName in brackets or accessing the va ...

Modal failing to update with latest information

My webpage dynamically loads data from a database and presents it in divs, each with a "View" button that triggers the method onclick="getdetails(this)". This method successfully creates a modal with the corresponding data. function getdetails(par) { ...

Using Angular Typescript with UWP causes limitations in accessing C# WinRT component classes

Currently, I am working on a UWP application built with Angular5 and I would like to incorporate Windows Runtime Component(Universal) classes into the application to access data from a table. import { Component,OnInit } from '@angular/core'; @C ...

Issue TS2322 presents itself when attempting to assign a value of type 'string, number, or Date' to a variable of type 'Date' after upgrading to Angular 16

I recently upgraded my project from Angular 11 to Angular 16 and encountered an issue with the DTO models generated using the NPM package "ng-swagger-gen" from the Swagger JSON file of the Web API. In my C# class on the Web API side, I have a DateTime fiel ...

Utilize the provider within the decorator function

Essentially, the challenge I am facing is passing an authService to the "verifyClient" function within the @WebSocketGateway decorator. Here is how it should look: @WebSocketGateway({ transports: ['websocket'], verifyClient: (info: { req: Inc ...

Handling click events on Datatable.net paging buttons

My goal is to capture the click event when one of the paging buttons on the Datatable is clicked in Angular. I'm not exactly sure how to go about accomplishing this! If I refer to this example, how can I adapt the code for Angular? Specifically, how ...

Definition for the type react-navigation-v6 <Stack.Group>

I'm having trouble figuring out the proper type definition for a Stack group that includes screens (refer to TestStack.Group and the nested TestStack.Screen). The navigation stack: const TestStack = createNativeStackNavigator<TestStackParamList> ...

Tips for generating a barcode with Crystal Reports in ASP.NET

Are you wondering how to generate a barcode with Crystal Reports in ASP.NET? ...

Is it possible to customize a directive to define the placeholder text for an input field with Angular Material?

Here is some sample HTML code: <md-input-container> <input mdInput myCustomDirective formControlName="email" > </md-input-container> My goal is to set the placeholder in my custom directive. I attempted to do this usi ...

Guide on Implementing Class on Dropdown in AngularFollow these steps to effectively utilize the

Currently, I am facing an issue with my Angular project. I am trying to implement a Directive that activates a dropdown menu. However, the 'open' class is deprecated in Bootstrap 3, and I am using Bootstrap 5. How can I transition to the 'sh ...

ActivatedRoute not receiving the parameter value

Having trouble retrieving the parameter from the route and passing it to a function within the component which then communicates with the service. Initially tried placing the parameter retrieval in the NgInit but moved it to the constructor, still no succ ...

Deciphering the .vimrc setup for tooltips and symbols in TypeScript

Currently, I have integrated the Tsuquyomi plugin for my typescript development in Vim. The documentation mentions tooltips for symbols under the cursor, which are working fine. The issue arises as I am using terminal-based Vim, and even if I were using a ...

Tips for positioning the labels in a sankey diagram for optimal alignment

When multiple values are the same in this scenario, such as 0, the labels start to overlap. Can anyone provide guidance on how to align these labels vertically? Ideally, I would like them to be positioned at the top of the node/bar. Highcharts.chart(&apos ...