Displaying data from backend in an Angular 7 textbox

I'm currently working with Angular 7 and I have managed to retrieve values from the backend. However, I am struggling to display these values in a textbox. Can anyone provide me with some suggestions on how to achieve this?

My tech stack includes Loopback and Angular 7.

file.component.ts

   ngOnInit() {
let userId = window.localStorage.getItem("editUserId");
if(!userId) {
  alert("Invalid action.")
  this.router.navigate(['list-user']);
  return;
}
alert(userId)
this.editForm = this.formBuilder.group({
  id: [''],
  name: ['', Validators.required],
  firstName: ['', Validators.required],
  lastName: ['', Validators.required],
  age: ['', Validators.required],
  salary: ['', Validators.required]
});
this.apiService.getUserById(+userId)
  .subscribe( data => {
    this.editForm.setValue(data);
    //alert(data)
  });
}

file.component.html

     <div class="hidden">
  <input type="text" formControlName="id" placeholder="id" name="id" class="form-control" readonly="true">
</div>
<div class="form-group">
  <label for="name">User Name:</label>
  <input type="text" formControlName="name" placeholder="name" name="name" class="form-control" id="name" readonly="true">
</div>

Answer №1

To update a value, you can use the following code:

this.editForm.controls['firstName'].setValue(data.firstName);

Alternatively, you can replace the setValue method with patchValue like this: this.editForm.patchValue(data);

For instance:

 var data= {firstName: 'Hien', lastName : 'Nguyen', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cda5a4a8a38daaa0aca4a1e3aea2a0">[email protected]</a>'};

 this.editForm .controls['firstName'].setValue(data.firstName);
 this.editForm .controls['lastName'].setValue(data.lastName);

Check out the demo here:

https://stackblitz.com/edit/angular-7-reactive-form-validation-test

Answer №2

In order to connect the input value with the component property, you will need to bind them together. If you can share a StackBlitz or another online editor with us, we can provide more specific assistance to address any issues you may be facing.

<div class="hidden">
  <input type="text" formControlName="id" placeholder="id" name="id" class="form-control" readonly="true">
</div>
<div class="form-group">
  <label for="name">User Name:</label>
  <input type="text" formControlName="name" placeholder="name" name="name" class="form-control" id="name" readonly="true" [ngModel]="editForm.name">
</div>

For further guidance on displaying component properties through interpolation, I suggest referring to this documentation.

Answer №3

Utilize the patch value API specifically designed for manipulating form objects!

this.editForm = this.formBuilder.group({
  id: [''],
  name: ['', Validators.required],
  firstName: ['', Validators.required],
  lastName: ['', Validators.required],
  age: ['', Validators.required],
  salary: ['', Validators.required]
});
this.apiService.getUserById(+userId)
  .subscribe( response => {
    this.editForm.patchValue({
         id: response.id,
         name: response.name,
         firstName: response.firstName,
         lastName:response.lastName,
         age:response.age,
         salary: response.salary
  });
}

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

Adding an icon to the contents of a specific column in Angular material

Struggling to figure out how to incorporate an icon into the data in the Status column using Angular material. Here is the markup of my page: <table mat-table [dataSource]="dataSource"> <ng-container *ngFor="let ...

Instantiate a fresh object using the new keyword followed by the Class constructor, and if desired,

I'm looking for a class that I can easily create new instances from and optionally assign properties using the constructor. For instance: class Person { name: string; age: number; constructor(props: {name?: string, age?: number}) { this.nam ...

Invoking a C# class file using Typescript

Incorporating TypeScript and Kendo Grid into my project, I am seeking guidance on how to invoke a method within a C# class object (specifically the ProcessData method in the Utility.cs object) from TypeScript. Can someone please advise me on how to accom ...

"Prior to authenticating the user, the Angular route guard is triggered

A route guard was successfully implemented to redirect users to the login page if they are not authenticated, with the login check being of type Observable. Everything works fine when a user is logged in and navigates to a protected page: { path: 'pr ...

Autoplay halts on Ionic 3 image slider following manual slide navigation

My Ionic 3 image slider has autoplay functionality that works perfectly. However, I've noticed that when I manually slide the images, the autoplay feature stops working. I have included my Ionic 3 code below. I would greatly appreciate any help on thi ...

Implementing a back button in an RTL layout with Ionic 2

Just starting an Ionic 2 app in Arabic language requires a RTL layout. I decided to go with the side menu template. Adding the following line for configuring the app to RTL perfectly changed everything's direction, except for the back button which st ...

angular 2 text box clearing functionality appears to be malfunctioning

I am currently working on implementing a reusable search box in Angular 2. Although the code is relatively basic, I am new to Angular 2 but have some experience with Angular 1. I am facing an issue where the value is not clearing when the text box is foc ...

Optimal approach for designing interfaces

I have a situation where I have an object retrieved from the database, which includes assignee and author ID properties that refer to user objects. As I transform a number into a user object, I am unsure about the best practice for defining the type of the ...

issue with duplicating DOM element using function

My situation is unique from the one described in this post. The code mentioned there is not functioning as expected when clicking the clone button. I have even provided a video explanation of how that code works. Unfortunately, I haven't received any ...

Sanitizing a string through manual effort

On my webpage, users can input text into a textarea. However, I want to ensure that the text they provide is properly sanitized before being saved as a string. I am struggling to understand how to manually sanitize this data using DomSanitizationService. ...

Unable to access file: EACCES: permission denied when trying to open '/Users/emilio/.ionic/daemon.log' - Error occurred due to lack of permissions

Hello everyone in the Ionic community! I've been working on an Ionic v3 project and everything was running smoothly. However, when I attempted to integrate the Geolocation module from @ionic-native/geolocation, I encountered an error message stating: ...

ngx: navigate to the specified URL once the user has been successfully logged in

I am faced with a dilemma where I must wait for my authentication server to return my token before calling my APIs. I am looking for a solution to ensure that my authState.token is not null before dispatching LoadMyStuffFromApi. I have implemented two res ...

Move forward state using navigateByUrl in Angular

I am looking to send data when changing the view using navigateByUrl like this: this.router.navigateByUrl(url, {state: {hello: "world"}}); Once in the next view, my goal is to simply log the hello attribute like so: constructor(public router: Router) { ...

What is the primary function of the platform-server module within Angular 2?

While exploring the AOT (ahead of time compilation) documentation at https://angular.io/docs/ts/latest/cookbook/aot-compiler.html#!#compile, I noticed a dependency on platform-server. What exactly is the function of this platform, when it seems like only ...

Breaking down nested arrays in typescript

After receiving a response from the service, the data included the following: "rows": [ [ "stravi/aa", "202001", "59", "51", "2558.98", "0.5358894453719162", "1.9204668112983725", "140", "2.346630 ...

Make sure to search for the "Not in" condition in an Angular 2 template list

I'm currently working with a template that looks like this: <span *ngIf="item.status !=='E1' && item.status !=='B' && item.status !=='R'">{{item.status_desc}}</span> Although the ngIf condit ...

What is the best way to set a checkbox to null instead of false using Angular?

I am currently developing a filtering system that allows users to select different parameters to filter through a list of items. For instance, the item list could be a collection of dishes with filters represented as checkboxes labeled as vegan, vegetaria ...

Angular nested routes allow for creating more complex and dynamic

I'm facing an issue with setting up nested routes in my myfile.routing.module.ts file. Whenever I try to access a specific route, it keeps redirecting me back to the home page. Below is the snippet of my code: routing.module.ts . . . const routes: R ...

Choosing the Right Language for AngularJS 2: TypeScript, JavaScript, or Dart?

AngularJS 2 is on the horizon, and the documentation recommends three languages: Typescript, Javascript, and Dart. As someone who primarily works with Javascript EcmaScript 5, I'm curious about the strengths and weaknesses of these three options. Cu ...

What is the most efficient method to iterate through Angular 4 using Bootstrap columns?

I'm trying to arrange my list into different columns using Bootstrap. The first row should have three columns The second row should have two columns The third row should have only one column Here is the code I have: <div *ngFor="let watch of L ...