Obtaining database information and utilizing setValue or patchValue

One way to retrieve data from a database and populate it into an input box is shown below:

Retrieving service

getStudentAddress() {
 const id = sessionStorage.getItem('userId');
 return this.http.get('http://localhost:8080' + '/student/' + id);
}

The getStudentAddress() function will fetch student data in an array format.

https://i.sstatic.net/0casF.png

To automatically display this data on an input box when the page loads, you can use the following method in your component:

ngOnInit() {

 // Here you can set the value from the database using setValue or patchValue
 this.studentForm.setValue({
  s_pNumber: '1234',
  s_address: '123',
  s_address2: '123',
  s_pCode: '123',
  s_city: '123',
  s_state: '123',
  s_country: '123'
});

Answer №1

To retrieve the observable value, you must first subscribe to the API call and then utilize patchValue to assign it to your reactive form. It is presumed that the names of your FormControl correspond with the properties in the object. In your component.ts file:

constructor(private crudService: crudService) { }

ngOnInit() {
  this.crudService.getStudentAddress().subscribe((response: any) => {
    this.studentForm.patchValue(response.data);
  });   
}

If you require further information on assigning values to your FormControl, feel free to check out my other response.

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

Ways to manage an rxjs observable reaction that may potentially have no data?

Currently, I am working with Angular2 and Ionic2 using typescript and have a requirement to manage responses from the backend service. The response may either be empty with http status 200 or it could be a json object containing an error message property ...

Error: The argument 'IParams' is not compatible with the parameter type 'IParams' in Typescript with NextJS14

I encountered an error in my code while using Prisma with Next.js 14 and TypeScript. The issue arises when trying to load product details via product ID. The error is captured in the screenshot below. Failed to compile. ./app/product/[productId]/page.tsx:1 ...

What is the procedure for incorporating a cookie jar into axios using typescript?

I encountered an issue while trying to add a cookie jar to an axios instance. The problem arises because the interface AxiosRequestConfig does not have a member named "jar". Is there any way to enhance the existing AxiosRequestConfig type or is there a wor ...

Ways to verify the input label in Angular version 4 and above?

I'm working on an Angular component that includes a form structured like this: <form> <label for="Name">Click me</label> <input type="text" id="Name" name="Name" /> <label for="Name2">Click me 2</label> &l ...

Adjust the icon's color after it has been clicked

How can I make the icon change color after it's clicked in Angular 4 with Bootstrap? I have icons displayed in panels using *ngFor loop and currently, when I click on an icon, it changes color in all panels. How do I make it change color only in the s ...

Trouble with embedding video in the background using Next.js and Tailwind CSS

This is the code snippet for app/page.tsx: export default function Home() { return ( <> <main className='min-h-screen'> <video muted loop autoPlay className="fixed -top ...

The functionality of Angular 4 routing is limited to directing to just one subsequent route at

I am encountering a peculiar problem with Angular 2 routing. I can successfully navigate to the next page, but for some reason, I am unable to navigate from that page. My application consists of 4 components: Home, Search Result, Profile, and Admin. Upon ...

The attribute 'status' is not found in the 'ServerResponse' type (TS2339)

I've attempted to develop an interface and install React types, but the only way it seems to work is when I write the code in JavaScript. However, within a TypeScript project, I encounter this error: Property 'status' does not exist on typ ...

Having trouble deploying my MEAN stack application on Heroku due to a MongoNetworkError: unable to establish a connection to the

Encountering difficulty connecting to MongoDB for application deployment, receiving error message "MongoNetworkError: failed to connect to server [localhost:27017] on first connect [Error: connect ECONNREFUSED 127.0.0.1:27017". What are potential issues ca ...

What is the best way to import and export modules in Node.js when the module names and directories are given as strings?

Here is the structure of my folder: modules module-and index.js module-not index.js module-or index.js module-xor index.js moduleBundler.js The file I'm currently working on, moduleBundler.js, is re ...

Tips for organizing my data upon its return into a more efficient structure

I need to restructure API data that is not optimized in its current format Unfortunately, I am unable to ask backend developers to make the necessary changes, so I am exploring ways to clean up the model locally before using it in my Angular 2 application ...

Issue during Docker build: npm WARN EBADENGINE Detected unsupported engine version

Currently, I am constructing an image based on mcr.microsoft.com/devcontainers/python:0-3.11-bullseye. In my docker file, I have included the following commands towards the end: RUN apt-get update && apt-get install -y nodejs npm RUN npm install np ...

Encountering Typescript issues following the transition from npm to pnpm

Currently, I am facing a challenge in migrating an outdated Angular JS project from npm to pnpm. The main issue I am encountering is related to typescript errors, particularly the error message that states: error TS2339: Property 'mock' does not ...

Tips for binding data to numerous dynamic controls

Implementing reactive forms in my Angular project allowed me to create a simple form for adding employee work hours and breaks. The challenge I encountered was the inability to bind data from break controls. In the .ts file export class AddAppointmentForm ...

How to delay setting a property in Angular 2 until the previous setter has finished execution

Hey there, I'm facing an issue with my component. Within my component, I have an input setter set up like this: @Input() set editStatus(status: boolean) { this.savedEditStatus = status; if (this.savedEditStatus === true && this.getTrigg === t ...

Alias in webpack for Typescript modules

I'm facing an issue where I need to assign an alias for 'Hammer' in my code. I've already included the necessary paths in my tsconfig file as shown below: { "compilerOptions": { "declaration": true, "noImplicitAny": false , ...

When a form contains a ViewChild element, changes to the ViewChild element do not automatically mark the

Let's set the stage: MainComponent.html <form #someForm > <input type="text" name="title" [(ngModel)]="mainVar" /> <child-component /> <input type="submit" [disabled]="someForm.form.pristine" /> </form> ChildComp ...

IE11 displaying empty placeholders instead of PrimeNG icons after deployment on server

Currently, I am in the midst of an Angular project that heavily relies on PrimeNg for various components. While everything runs smoothly when testing the project locally across all browsers (including IE11 and Chrome), a hiccup arises once the project is ...

The NgStyle doesn't seem to be refreshing properly within the observable's complete callback

Managing an element's height based on a web call response is presenting a challenge. Initially, the height style was set to 0px. public voiceCommCockpitHeight = { height: '150px' }; The code snippet showcasing this functionality is as foll ...

Is it possible to modify the background-image using Typescript within an Angular project?

I have been struggling to change the background image in my Angular project using Typescript. I attempted to make the change directly in my HTML file because I am unsure how to do it in the CSS. Here is the line of code in my HTML file: <div style="ba ...