Struggling to retrieve the value of a text field in Angular with Typescript

In the Angular UI page, I have two types of requests that I need to fetch and pass to the app.component.ts file in order to make a REST client call through the HTML page.

Request 1:

Endpoint: (GET call)

http://localhost:8081/api/products?productId=7e1308ba2b9af

In the app.component.html file, I have created a text field as shown below:

<div>
    <input type="text" placeholder="Product ID" class="user_id_text"/>
</div>
<div>
    <input type="submit" value="submit"/>
</div>

Output:

https://i.sstatic.net/hEqpr.png

I have written the following code and verified it with a hard-coded value to ensure it works as expected.

app.component.ts:

ngOnInit(): void{

    this.http.get('http://localhost:8081/api/products?productId=7e1308ba2b9af').subscribe(data =>{ 

        console.log(data);
    });
}

The code above returns a data array with the proper response. However, the productId value is hard-coded (7e1308ba2b9af). I want to retrieve this value from the HTML text box when the user clicks the submit button and pass it as a query parameter to execute the request.

Request 2:

I need to obtain the following JSON format from a text box and send it as a JSON request body to the endpoint URL below.

Endpoint: (PUT call)

https://localhost:8081/api/updateRecord

Request JSON:

{
    "productId": 234242882,
    "purchaseDate": "2019-12-20",
    "status": "dispatched"
}

I aim to create a text field where the user can input the JSON file above and upon clicking the submit button, trigger the endpoint mentioned.

Being new to Angular, I am uncertain on how to implement this. Despite searching online, I struggle to comprehend the solutions provided. Any guidance or explanation on how to resolve this issue would be greatly appreciated.

Answer №1

To fulfill request 1:

Assign an ID to your input tag and use the following code snippet:

let value = (<HTMLInputElement>document.getElementById("idproduct")).value

Alternatively, you can use:

let value = document.getElementById("idproduct").innerHTML

Answer №2

Implementation of User Input Handling

Utilizing ReactiveFormsModule allows direct retrieval of user input values for dynamic feeding to the API. Importing HttpClientModule is also essential for this process.

To implement this functionality, the following steps need to be taken:

app.module.ts

import {ReactiveFormsModule} from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';


@NgModule({
  declarations: [...],
imports: [...,ReactiveFormsModule, HttpClientModule],
providers: []...

Once ReactiveFormsModule and HttpClientModule are imported, FormBuilder and FormGroup can be used to dynamically track user input, and HttpClient to send GET requests to the API.

app.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { HttpClient, HttpHeaders } from '@angular/common/http';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
   productIDForm: FormGroup;
    httpHeaders: new HttpHeaders({
      'Content-Type': 'application/json',
   })
   constructor(
     private formBuilder: FormBuilder,
     private http: HttpClient
   ) { }



ngOnInit() {
     this.productIDForm = this.formBuilder.group({
       'productID': [null, [Validators.required, Validators.nullValidator]]
    })
  }

 onSubmit() {
if (this.productIDForm.invalid) return;

this.getProduct(this.productID.get('productID').value).subscribe(
  (res) => {
    console.log(res);
  },
(err) => {
  console.log(err);
 )
 }



getProduct(productID: string): Observable<any> {
        return this.http.get(
          `http://localhost:8081/api/products?productId=${productID}`,
       { headers: this.httpHeaders }

       )
    }
}

Binding the input field to productIDForm is the next step.

app.component.html

<form [formGroup]="productIDForm">
      <input formControlName="productID" type="text" class="user_id_text"/>
    </form>
    <div>
      <input (click)="onSubmit()" type="button" />
    </div>

Dynamic User Input Handling for API Interaction

Utilizing ReactiveFormsModule, FormBuilder, and FormGroup facilitates dynamic user input retrieval and binding for API PUT requests.

app.component.ts

    import { Component, OnInit } from '@angular/core';
    import { FormBuilder, FormGroup, Validators } from '@angular/forms';
    import { HttpClient, HttpHeaders } from '@angular/common/http';
    import { Observable } from 'rxjs';


    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })

    export class AppComponent {

    productIDForm: FormGroup;
        httpHeaders: new HttpHeaders({
          'Content-Type': 'application/json',
       })

   constructor(
     private formBuilder: FormBuilder,
     private http: HttpClient
   ) { }



ngOnInit() {
     this.productDetailsForm = this.formBuilder.group({

'productID': [null, [Validators.required, Validators.nullValidator]],
'purchaseDate': [null, [Validators.required, Validators.nullValidator]],
'status': [null, [Validators.required, Validators.nullValidator]]
})

}


onSubmit() {

    if (this.productDetailsForm.invalid) return;
    let recordNewDetails = {
        "productId": this.productDetailsForm.get('productID').value,
        "purchaseDate": this.productDetailsForm.get('purchaseDate').value,
        "status": this.productDetailsForm.get('status').value
    }
  recordNewDetails = JSON.stringify(recordNewDetails);

this.updateRecord(recordNewDetails).subscribe(
  (res) => {
    console.log(res);
  },
(err) => {
  console.log(err);
 )
 }

updateRecord(productDetails: {}): Observable<any> {
        return this.http.put(
          `https://localhost:8081/api/updateRecord`m
           productDetails,
          { headers: this.httpHeaders }

       )
    }
}

app.component.html

<form [formGroup]="productDetailsForm">
      <input formControlName="productID" type="text" class="user_id_text"/>
      <input formControlName="purchaseDate"  type="date">
      <select formControlName="status">
          <option disabled>Select Status Option</option>
          <option>Dispatched</option>
      </select>
    </form>

    <div>
      <input (click)="onSubmit()" type="button" />
    </div>

Answer №3

To connect an input to a variable, make use of [(ngModel)]:

<div>
  <input type="text" [(ngModel)]="productId" placeholder="Product ID"
         class="user_id_text"/>
</div>

To link a button to a function, use (click):

<div>
  <input type="submit" (click)="getById(productId)" value="submit"/>
</div>

Within the controller:

ngOnInit():void {    
    this.http.get('http://localhost:8081/api/products?productId=7e1308ba2b9af').subscribe(data =>{     
      console.log(data);
    });
}

getById():void {
    const base:string = "http://localhost:8081/api/products";       
    const url:string = `${base}?productId=${this.productId}`;
    this.http.get(url).subscribe(data =>{ 
        console.log(data);
    });    
}

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 causes the object to be updated with new values when I update reference variables in JavaScript?

Imagine having an object named x with values x = { a: 'abc', b: 'jkl' }, Next, I am assigning this object x to a new local variable y using var y = x. Now, when the value of var y changes as y.a = 'pqr', y.b = 'xyz&apos ...

Obtaining numerous data points in a multi-select element within HTML

Struggling with determining the values of multiple <select> tags in an HTML file simultaneously? function knowAllValues(){ var color_element = document.getElementById("color"); var size_element = document.getElementById("size"); ...

Using Owl Carousel 2 and other jQuery plugins in Angular 4 TypeScript classes: A step-by-step guide

I have been facing challenges trying to incorporate jQuery plugins into an Angular 4 TypeScript class. Despite multiple attempts, I have not been able to achieve my goal. I tried various methods, but the HTML component view in Angular 4 does not seem to s ...

Having trouble with the initial tap not being recognized on your mobile browser?

When using mobile web browsers (specifically chrome and firefox on iOS), I am experiencing an issue where the hamburger menu does not trigger when tapped for the first time. For a simplified version of the HTML/CSS/JS code, you can check it out at: https ...

Deactivate certain choices in React Select

Encountering difficulties disabling specific options in a large list within a React Select component. A total of 6,500 options are loaded into the select element. Initially, there were issues with search functionality lagging, but this was resolved by impl ...

Error: Expected an expression but found a parsing error in the eslint code

interface Address { street: string, } export const getAddress = (address: Address | null) : string => address?.street ? `${address?.street}` : '0000 Default Dr'; Why am I receiving the error message Parsing error: Expression expected ...

The Render function in ReactJS is not getting refreshed

My goal is to implement a chat feature using material UI. I have set up a function where users can submit new chat messages, which then go through the reducer and are stored in the redux store. The process seems to be working fine, except for the fact that ...

There was an issue with the NextJS axios request as it returned a status code

I'm currently in the process of developing an application with NextJS and Strapi In my project, I am fetching data from Strapi using Axios within NextJS Next: 14.0.4 Axios: ^1.6.5 Strapi: 4.17.1 Node: 18.17.0 Here is the code snippet: import axios f ...

Streamline the process of renaming or remapping keys in a collection of JavaScript/JSON objects

Structured JSON data is essential. Imagine using JSON.parse(): [ { "title": "pineapple", "uid": "ab982d34c98f" }, { "title": "carrots", "uid": "6f12e6ba45ec" } ] The goal is to transform it by changing titl ...

Exploring the power of JQuery's $.post() function and the magic

In order to utilize the GroupMe API (), the following command is required: $ curl -X POST -H "Content-Type: application/json" -d '{"source_guid": "frgfre", "text":"alala"}' https://api.groupme.com/v3/groups/ID/messages?token=YOUR_ACCESS_TOKEN I ...

When a model.find is passed as an argument to be invoked, it results in an error

After working with ExpressJS for a while, I decided to explore using Mongoose alongside it. In the callback of my queries where I handle errors like this: function( error, data ) {...} , I found myself repeating code. To streamline this process, I created ...

Error: Peer Dependency Not Fulfilled

Warning: The package @schematics/[email protected] has a peer dependency of @angular-devkit/[email protected], but it is not installed. You will need to handle the peer dependencies manually. I initially installed Angular CLI using npm instal ...

Loading React router on every route page

<BrowserRouter> <div> <Route path={"/"} component={Home} /> <Route path={"/component"} component={AnotherComp} /> <Route path={"*"} component={NotFound} /> </div> </ ...

Is there a way to instruct Babel to generate polyfills such as `__createClass` only once for multiple files?

In my project, I have multiple ES6 files, each containing at least one class. For every file, the __createClass, __interopRequireDefault, and __classCallback polyfilling functions are generated. I plan to concatenate them using browserify, but it seems re ...

What is the purpose of specifying http://localhost:3000 when accessing API routes in Next.js?

I created an API route within the pages directory of my NextJS project. It is functioning properly as I am able to retrieve data by directly accessing the URL like http://localhost:3000/api/tv/popular. My goal is to fetch this data using getStaticProps and ...

Warning: The DataTables alert has been triggered for table ID DimStatus. It is indicating that an unknown parameter, 'Code', has been requested for row 0 and column 0 during the initialization

https://i.stack.imgur.com/yEpSp.pngI am encountering an error while attempting to display my data in a datatable. The structure of my table is as follows: [Table("DimStatus", Schema = "dmg")] public class PolicyState { [Key] ...

How can I prevent an Angular 2+ app from loading until the APP_INITIALIZER has completed its execution?

While I have managed to call a service before the root component loads, I am struggling to find a way to make the whole app wait until the service completes successfully. Essentially, I am looking for a way to make it a synchronous call. The service is loa ...

Ensuring a button (class) is in active hover mode when the document loads

My website features 4 clickable service buttons on the homepage, each with a unique hover effect (background-color change) when users interact with them. While this setup works well overall, I am looking to highlight the FIRST button as the most important ...

Creating a scrolling effect similar to the Nest Thermostat

After researching countless references, I am determined to achieve a scrolling effect similar to the Nest Thermostat. I came across this solution on this JSFiddle, but unfortunately, the parent element has a fixed position that cannot be utilized within my ...

Implement a jQuery slider that pauses on hovering

Currently, I am grappling with the clearInterval function in a small jQuery project. To better illustrate the issue, I have created a jsFiddle example: http://jsfiddle.net/eWTSu/ While the rotation works smoothly, I encountered an obstacle when hovering ...