Getting Form Value in Component.ts with Angular 5

How can I incorporate an input form into my component while constructing a form?

<div class="row">

<div class="col-md-6 offset-md-3 text-center>
  <h2> Login Form </h2>
<form (ngSubmit)="OnSubmit(login.value,password.value)" #loginForm="ngForm">
  <div class="form-group">
    <label for="exampleInputEmail1">Login</label>
    <input type="text" class="form-control" id="exampleInputEmail1"  ngModel name="login"  aria-describedby="emailHelp" placeholder="Login">
  </div>
  <div class="form-group">
    <label for="exampleInputPassword1">Password</label>
    <input type="password" class="form-control" id="exampleInputPassword1" required  ngModel name="password" placeholder="Password">
  </div>
<!---->
<button type="submit" class="btn btn-primary" [disabled]="!loginForm.form.valid">Submit</button>

</form>
</div>

</div>

This is a straightforward login form that corresponds with the login.component.ts class.

    import { Component, OnInit } from '@angular/core';
    import { Router } from '@angular/router';
    import { NgForm } from '@angular/forms';
    import { FormGroup, FormControl } from '@angular/forms';
    import { ReactiveFormsModule } from '@angular/forms';


    import { HttpErrorResponse } from '@angular/common/http';
    import { UserService } from '../auth/user.services';

    @Component({
      selector: 'app-login',
      templateUrl: './login.component.html',
      styleUrls: ['./login.component.css']
    })
    export class LoginComponent implements OnInit {
      ngForm: NgForm;

      isLoginError : boolean = false;
      constructor(private userService: UserService, private router: Router) { }

      ngOnInit() {


      }

    // Execute this when submit login form
    OnSubmit(login,password){
        //this.userService.login(userName,password).subscribe((data : any)=>{
        // localStorage.setItem('userToken',data.access_token);
        console.log('Submit login form: login => '+login+' password => '+password );

}

}

Here is my app.module.ts file:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { FormsModule} from '@angular/forms';
import { HttpModule } from '@http/http';

import { AppComponent } from './app.component';
import { AppNavbarComponent } from './app-navbar/app-navbar.component';
import { LoginComponent } from './login/login.component';
import { AppRoutingModule } from './/app-routing.module';
import { HomeComponent } from './home/home.component';
import { MonitoringComponent } from './monitoring/monitoring.component';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';



import { UserService } from './auth/user.services';
import { AuthGuard } from './auth/auth.guard';
import { AuthInterceptor } from './auth/auth.interceptor';


@NgModule({
  declarations: [

    AppComponent,
    AppNavbarComponent,
    LoginComponent,
    HomeComponent,
    MonitoringComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    NgbModule.forRoot(),
    AppRoutingModule,
    HttpClientModule,
    HttpModule
  ],
  providers: [UserService,AuthGuard,HttpClientModule
     ,
     {
       provide : HTTP_INTERCEPTORS,
       useClass : AuthInterceptor,
       multi : true
  }],
  bootstrap: [AppComponent]
})
export class AppModule { }

Upon clicking the submit button on the login form, the login and password fields return as undefined. What am I overlooking?

Answer №1

Here is a template to update your login form:

<form (ngSubmit)="OnSubmit(loginForm)" #loginForm="ngForm">

In the OnSubmit() function, make sure to access the form values correctly:

 OnSubmit(form){
            //this.userService.login(userName,password).subscribe((data : any)=>{
            // localStorage.setItem('userToken',data.access_token);
            //console.log('Submit login form: login => '+login+' password => '+password );
         console.log(form.value);

    }

Add binding for ngModel in your input element:

<div class="form-group">
    <label for="exampleInputEmail1">Login</label>
    <input type="text" class="form-control" id="exampleInputEmail1"  [(ngModel)]="login" name="login"  aria-describedby="emailHelp" placeholder="Login">
  </div>

Remember to define login and password variables in your component class:

 export class LoginComponent implements OnInit {
      ngForm: NgForm;
      login: string;
      password: string;
      isLoginError : boolean = false;
      constructor(private userService: UserService, private router: Router) { }

    ...

}

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

Tips for setting ngModel and name attributes in an angular test for a custom component

Just getting started with angular. I recently developed a custom component that implements the ControlValueAccessor to allow developers to easily access its value. Here's an example of how it can be used: <app-date [label]="'Date 2&apos ...

Display Custom Form Fields Based on Radio Button Selection

Being a new user of Yii, I've been immersed in it for less than 2 months. Currently, my focus is on creating a registration form that initially displays only 2 radio buttons - one representing a Person and the other an Organization. Upon selecting eit ...

Tips for addressing the issue of mat-list-item not occupying the entire row's space

Hello everyone, I am currently trying to render an article.component.html within my article-list-component.html in a list format. When I use plain HTML, it renders correctly as shown in picture 1: Title - author - Date Here is the code for my article-list. ...

Conceal Columns in DevExtreme with Angular2 EditMode

Is there a way to conceal a DataGrid Column while in EditMode by utilizing DevExtreme and Angular2? <h3>Test</h3> <dx-data-grid id="gridContainer" [dataSource]="xxx" [allowColumnReordering]="true" [allowColumnResizing]="true" [rowAltern ...

Attaching the JSON data to ngModel in Angular 2

I have received a json response containing various fields, including the rewards.rewardName value. I'm trying to figure out how to bind this specific value to [(ngModel)] in Angular 2. [ { "id": 18, "gname": "learning ramayanam", "goalCat ...

What is the best way to approach writing a shared value that is utilized across multiple files in Angular?

I am currently implementing Angular for the front end of my project. One challenge I'm facing is managing a single value, such as a 'role id', that needs to be used in multiple .ts files within Angular. Can anyone suggest an efficient way ...

Is it possible to navigate to a particular step during an Angular IntroJS event?

Whenever I attempt to navigate to a specific step from within the IntroJS onexit event, it seems to cause confusion and display the incorrect step along with the highlighted element. I have defined my steps using JSON, with a total of 8 steps: [{ elem ...

No changes made to Observable when it's empty

I encountered an unusual issue with the rxjs "filter" in my development environment: SAP ComposableStorefront / Spartacus "~2211.21.0" angular 17.2.0 Currently, I am on a product detail page and applying a filter to my Observable in the following manner: ...

Incorporating a CSS Module into a conditional statement

Consider the following HTML structure <div className={ `${style.cell} ${cell === Player.Black ? "black" : cell === Player.White ? "white" : ""}`} key={colIndex}/> Along with the associated CSS styles .cell { ...

Is there a specific side effect that warrants creating a new Subscription?

Recently, I had a discussion on Stack Overflow regarding RxJS and the best approach for handling subscriptions in a reactive application. The debate was whether it's better to create a subscription for each specific side effect or minimize subscriptio ...

Turning an angular API into a synchronous one: A step-by-step guide

My goal is to perform consecutive http calls to a REST service, with each call requiring a unique valid token in the header. The challenge arises when multiple components initialize simultaneously and make "get" calls at the same time using the same token. ...

Angular's Enhanced Feature: Selecting Multiple Columns

Looking for an open-source Angular library that can display items in multiple columns rather than each item spanning across multiple columns. Many libraries support tabular display, but the challenge is to find one that arranges items in multiple columns. ...

Struggling to apply custom styles to ng-content? Find out why the ::ng-deep selector

Attempting to customize the appearance of elements inside <ng-content> within anuglar2 <au-fa-input > <input type="text" class="form-control" placeholder="email" #input> </au-fa-input> In the CSS of the au-fa-input component, ...

Creating a contact form in WordPress that triggers a separate PHP file

I've been working on integrating a small contact form into the sidebar of my WordPress site. After moving the code from its original HTML file to the appropriate WordPress PHP files, everything seems to be functioning correctly except for the contact ...

Uploading an image with jQuery through Ajax form submission

When I try to add a new family member using a form with PHP and jQuery AJAX, the data gets posted but the image does not get uploaded. This is my HTML form that posts the data using AJAX (the issue is with the input type file): <form id="form_add_fami ...

What is the proper way to indicate the pointer to the current element within the array?

How can I modify a code that displays a list of posts? import React from "react"; type respX = { "id": any, "userId": any, "title": any, "body": any, } interface PropsI { } interface StateI { data: respX []; } export class Compone ...

Unable to loop through using ngFor

I have a component that retrieves data from the back-end and groups it accordingly. Below is the code snippet: getRecruitmentAgencyClientPositions(): void { this._recruitmentAgencyClientsService.getRecruitmentAgencyClientPositions(this.recruitmentAge ...

Utilizing Typescript generics with an optional second parameter

Learning about generics in typescript has been quite challenging for me. However, I was able to make it work successfully. export type Events = { LOGIN: undefined NAVIGATION: { screen: string } SUPPORT: { communication_method: 'chat&ap ...

Having difficulty importing the WebRTCAdaptor from the antmedia package stored in the node modules directory into an Angular Typescript file

An error is appearing indicating that: There seems to be a problem finding a declaration file for the module '@antmedia/webrtc_adaptor/js/webrtc_adaptor.js'. The file 'D:/web/node_modules/@antmedia/webrtc_adaptor/js/webrtc_adaptor.js' ...

Angular's trio of services tied in a circle of dependency

I'm encountering an issue with my angular project. These warnings keep popping up: WARNING in Circular dependency detected: src\app\core\http\content.service.ts -> src\app\core\http\domain.service.ts -> ...