[SOLVED] Angular returning of a single user property from the database

Issue

I am trying to build an app using ASP.NET as the Back End (API) and Angular to build the Front End of my app.

Here are my controllers in the API to get the list of the users respectively a single user from the database.

    [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);
    }

In Angular in the component’s .ts file I’ve added the following code:

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);
        })
  }

In the .html file of the component I have then added the following snippet and managed to return a list of all names of the users in the database.

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

My problem is now that I want to return a property (the name property for example) from a single user in another component.

Here is the .html file:

<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 of that 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 want to return the property of a single user( that is stored in the database) in the textbox. Any ideas how can I do this?

Solution

Add ngModel to your input control:

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

And also add FormsModule to your AppModule class

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

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

Answered By – Khumo Mogorosi

Answer Checked By – Dawn Plyler (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *