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

Pass JSON data from Angular service to component

I have encountered a challenge while trying to pass JSON data from my API service to a component without directly subscribing in the component. The issue arises when attempting to access the data outside of the subscription block, as it returns something u ...

Is it feasible to implement early-return typeguards in Typescript?

There are instances where I find myself needing to perform type checks on variables within a function before proceeding further. Personally, I try to minimize nesting in my code and often utilize early-return statements to keep the main functionality of a ...

Using JavaScript to place a particular tag at a designated position

I have a string that looks like this: var txtstr='<p>Text 1</p><p>&nbsp;</p><p>Text &nbsp;2</p><p>&nbsp;</p><p>Text 3&nbsp;</p>'; I have an <img src=..../> tag and ...

How to effectively implement form-control with mat-radio-group?

UPDATE: Check out my code on stackblitz I'm facing an issue with my form layout. The form control rows are overlapping with the radio button rows. I need help to resolve this problem. Here is a snippet of my code: <form [formGroup]="formGroup" (n ...

Inferring object types through direct values

This code example has a lot of detail: interface Coordinate { latitude: 40.7128; longitude: -74.0060; } const location: Coordinate = { latitude: 40.7128, longitude: -74.0060, }; // The inferred type would have been // { x: number; y: number; } I ...

Which data types are needed for the HttpRequest in my interceptor for Angular 10 when using strict mode?

I've been delving into the realm of strict mode in Angular 10, which introduces the "no-any" tslint rule. I've put in the effort to eliminate the any type from my application, but I'm unsure what types I should use for the HttpRequ ...

Can a Typescript class type be defined without explicitly creating a JavaScript class?

I am exploring the idea of creating a specific class type for classes that possess certain properties. For example: class Cat { name = 'cat'; } class Dog { name = 'dog'; } type Animal = ???; function foo(AnimalClass: Animal) { ...

Tips on sending various properties to makeStyles() using TypeScript

After learning how to pass 1 prop to makeStyle() from a resource, I decided to try passing in 2 props for my project. However, I encountered an error stating cannot find name 'props'. Any assistance on this issue would be greatly appreciated! con ...

Describing a property of an interface as the determined form of a conditional type that is generic

I am currently working on defining an interface that includes a method with a conditional function definition. For example: interface Example<T> { func: T extends string ? () => string : () => number; } class ExampleClass<T extends str ...

Node.js serves an Angular application without the need for additional JavaScript scripts

After developing an Angular application with a node.js server, I encountered an issue where the browser displayed the HTML code served by the server as text instead of rendering the web page correctly. This problem arose when I built the Angular project in ...

Strategies for handling multiple HTTP requests in Angular using RXJS

Within this demonstration application, we have the following structure: A list of articles (loaded upon page initialization) Each article contains a nested object called detail, which is loaded lazily Clicking on an article item will load its details. H ...

Discovering the existence of a child route in Angular

My goal is to implement a redirect for the User if they navigate to the wrong child route. I've set up a guard for a child component that requests data from an API, but I'm unsure how to handle the case where the data does not exist. I want to ei ...

Tips for boosting ViteJs development mode performance

One issue I am facing is the slow server performance during development mode. After starting the server and opening the page in my browser, I have to wait 3–6 minutes for it to load! Initially, ViteJs downloads a small amount of resources, but then the ...

How to format decimals in Typescript/Angular with a pipe: comma or dot?

I've recently developed a custom pipe and I'm looking to enhance it by adding commas or periods to thousands values. For instance, 1000 should be displayed as either 1,000 or 1.000. Here is the code snippet for my custom pipe: import { Pipe, Pi ...

Employing the ngFor directive, insert two elements onto a single row, then proceed to generate a fresh

For some time now, I've been attempting to loop through an array of objects using *ngFor and place two elements inside each row. The goal is to generate a new row after every two components have been added. Here's what I've attempted so far ...

Property finally is missing in the Response type declaration, making it unassignable to type Promise<any>

After removing the async function, I encountered an error stating that the Promise property finally is missing when changing from an async function to a regular function. Any thoughts on why this would happen? handler.ts export class AccountBalanceHandle ...

Sending data to the makeStyle function in TypeScript

How can I set the style of backgroundImage in my React component based on the value of post.mainImage? Here is the code snippet: import React from 'react'; import { Post } from '../interfaces'; import { makeStyles, createStyles, Theme ...

"Trouble with Bootstrap Collapse function - Utilizing ng-bootstrap, eliminating the need for JQuery

In my Angular 8 project, I have Bootstrap 4.3.1 and ng-bootstrap 5.1.1 integrated. As per the ng-bootstrap documentation, including ng-bootstrap in your project eliminates the need to manually add jQuery, as it is encapsulated by ng-bootstrap and not requ ...

React: Content has not been refreshed

MarketEvent.tsx module is a centralized controller: import * as React from 'react'; import EventList from './EventList'; import FullReduce from './FullReduce'; import './MarketEvent.less' export default class Mark ...

Is there a way to display a variety of images on separate divs using *ngFor or another method?

I have created a custom gallery and now I would like to apply titration on the wrapper in order to display a different image on each div. Currently, my code is repeating a single image throughout the entire gallery. HTML <div class="wrapper" ...