Struggling with fetching the email value in .ts file from ngForm in Angular?

I'm trying to retrieve the form value in my .ts file, but I am only getting the password value and not the email. Here is the code snippet:

<div class="wrapper">
      <form autocomplete="off" class="form-signin" method="post" (ngSubmit)="loginForm.form.valid && onSubmit(loginForm)" #loginForm="ngForm">
        <div class="text-center mb-4">
            <h1>Sign In</h1>
        </div>

        <div class="form-label-group">
            <label>Email</label>
            <input 
              type="email" 
              id="input-email" 
              [(ngModel)]="adminemail" 
              #admin_email="ngModel" 
              class="form-control" 
              placeholder="Email address" 
              autocomplete="email" autofocus [ngModelOptions]="{standalone: true}">
        </div>

        <div class="form-label-group">
            <label>Password</label>
            <input 
              type="password" 
              class="form-control" 
              placeholder="Password" 
              autocomplete="new-password" 
              name="password"
              id="input-password"
              [(ngModel)]="password">
        </div>
        <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
        <div>
          <p>
            <a routerLink='/pages'>Forgot Password</a>
          </p>
        </div>
    </form>
</div>

The .ts file contains this .html code where I'm using NgForm from '@angular/forms':

import { NgForm } from '@angular/forms';
...
...
onSubmit(form: NgForm) {
  console.log(form.value)
}

{password: "123456"}

However, in the console log, I only see the value of the password field and not the email. Is there something I'm missing?

Answer №1

When implementing two-way data binding, it's important to define the variables adminemail and password in the .ts file. Then, you can handle submission by adding the following to your code:

onSubmit() { 
   console.log(this.adminemail); 
   console.log(this.password);
}

Answer №2

To implement the form control in Angular, you can create a FormGroup and specify the properties for it.

.html file

<form bind-formGroup="checkoutForm" (ngSubmit)="onSubmit(checkoutForm.value)">
        <div>
            <label for="name">Name: </label>
            <input id="name" type="text" formControlName="name" />
        </div>
        <div>
            <label for="address">Address: </label>
            <input id="address" type="text" formControlName="address" />
        </div>

        <button class="button" type="submit">Purchase</button>
    </form>

.ts File


export class CartComponent implements OnInit {
    selectedProducts: ProductDto[] = [];
    checkoutForm: FormGroup;

    constructor(private cartService: CartService, private formBuilder: FormBuilder) {
        this.checkoutForm = this.formBuilder.group({
            name: '',
            address: ''
        });
    }

    ngOnInit() {
        this.selectedProducts = this.cartService.getProductsFromCart();
    }

    onSubmit(customerData: UserDto): void {
        // Process Checkout Data here
        console.warn(`Your order has been submitted with Name: ${customerData.name} Address: ${customerData.address}`);

        this.selectedProducts = this.cartService.clearSelectedProducts();
        this.checkoutForm.reset();
    }

}

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

Integrating HTTP JSON responses into HTML using Ionic 2, Angular 2, TypeScript, and PHP: A comprehensive guide

Currently in the midst of developing my first Ionic 2 app, however, my understanding of typescript is still limited.. I aim to execute the authenticate() method within my constructor and then to: Retrieve the entire JSON response into the textarea and/o ...

I am currently facing challenges retrieving data from a post request in my Angular/Typescript frontend application connected to an ASP.NET backend

I am currently working on a web application that relies on backend processing. To communicate between my Angular(v14)/Typescript front end and an ASP.NET backend, I am sending a post request. Backend Code [HttpPost] public async Task<string> Process ...

How can Angular components that are not directly related subscribe to and receive changes using a declarative approach?

Here's the issue at hand: I'm facing a problem with my Dashboard component. The Dashboard consists of a Sidebar and Navbar as child components. On the Sidebar, I have applied a custom permission directive to the links to determine if the user ha ...

Attempting to authenticate with Next.js using JWT in a middleware is proving to be unsuccessful

Currently, I am authenticating the user in each API call. To streamline this process and authenticate the user only once, I decided to implement a middleware. I created a file named _middleware.ts within the /pages/api directory and followed the same appr ...

TypeScript types for d3 version 4

I am currently working on a d3 project and to simplify the development process and reduce errors, I decided to implement TypeScript. Using d3 v4, I initially faced issues with incorrect type definitions which led to errors like d3 not having a definition ...

Find out whether the page was reloaded or accessed directly through a hyperlink

I need to find out if the page was accessed directly via a link. If it was, I need to perform a certain action. However, my current implementation is not working as intended, as even a page refresh triggers this action. Is there an alternative method to ch ...

Error message: "Function call failed in Angular model getter"

Here is the structure of my model: export class User { public username: string; private email: string; constructor() { this.username = undefined; this.email = undefined; } public getUsername(): string { return this.u ...

The EventEmitter in Angular 8 is prohibiting the emission of an Object

Is there a way I can emit an Object instead of primitive data types? I have an object const amount = { currenty: 'USD', total: '10.25' }; that I need to emit to the parent component. export class MyChildComponent implements OnInit { ...

There was an issue locating the moment/ts3.1-typings/moment module

Encountering an ERROR after updating Angular version: Could not resolve moment/ts3.1-typings/moment in node_modules/ngx-daterangepicker-material/ngx-daterangepicker-material.d.ts ...

Assigning value to a member variable in a TypeScript Angular class

Currently, I am in the process of learning Angular. To enhance my skills, I am developing a simple web application using Angular and Spring Boot. One challenge I encountered is assigning a variable to the member variable of a Class. import { Injectable } f ...

The state array is rejecting the value from the other array, resulting in null data being returned

I am currently attempting to extract image URLs from an HTML file input in order to send them to the backend and upload them to Cloudinary. However, I am facing an issue where despite having the imagesArr populated with images, setting the images state is ...

Tips for setting up a React TypeScript project with custom folder paths, such as being able to access components with `@components/` included

I'm looking to streamline the relative url imports for my React TypeScript project. Instead of using something messy like ../../../contexts/AuthContext, I want to simplify it to just @contexts/AuthContexts. I attempted to update my tsconfig.json with ...

Troubleshooting the issue of Angular2's http withCredentials not functioning as expected

Utilizing Angular2's HTTP module, I am sending HTTP requests. Once a user logs in, the backend server creates a cookie session which is then used by the frontend to send subsequent requests. The Angular code snippet is outlined below: get(url: string ...

Combine arrays using union or intersection to generate a new array

Seeking a solution in Angular 7 for a problem involving the creation of a function that operates on two arrays of objects. The goal is to generate a third array based on the first and second arrays. The structure of the third array closely resembles the f ...

Node.js encountering an error caused by a lengthy SQL procedure execution, triggered by a POST request initiated from

Currently, my website utilizes Angular, NodeJs, and a SQL database. Most of the site's calls are made from the frontend to the backend and everything runs smoothly. However, I encountered an issue when running a stored procedure that had a longer proc ...

The best way to access the value of a fulfilled Promise while debugging

I've been using this loopback application in my IntelliJ IDE. I set a breakpoint at the promise in calculator.controller.ts, where the code looks like this: @get('/multiply/{intA}/{intB}') async multiply( @param.path.integer('in ...

Confirm that the user has interacted with every input

When it comes to validating a form, you have the ability to determine if a user has interacted with an input field or checkbox (using X.touched). Is there a built-in validator that requires a user to specifically interact with each input field at least onc ...

Avoid triggering onClick events on all rows when clicking, aim for only one row to be affected per click

I have a unique situation where I have a table containing rows with a button in each row. When this button is clicked, it triggers an onClick event that adds two additional buttons below the clicked button. The Issue: When I click on a button, the onClick ...

angular triggering keyup event multiple times

Currently, I am working on a datalist feature. Whenever the user types something into the input field and releases a key, a GET request is made to retrieve an array of strings which are then displayed in the datalist. <input type="text (keyup)=&quo ...

Unable to execute OAuth2 with Okta using angular-oauth2-oidc framework

Looking to create an authentication module for an Angular application using Okta as the identity provider and implementing the angular-oauth2-oidc flow. Following a guide here: . However, encountering errors when running the web app. How can I troubleshoot ...