I am experiencing difficulties with my data not reaching the function in my component.ts file within Angular

My current project involves integrating Google Firebase to handle the login functionality. I encountered an issue where the data inputted from the HTML page to the component.ts file was not being processed or reaching Firebase. However, when I initialized the variables, the connection worked smoothly.

components.ts

    import { Component, OnInit } from '@angular/core';
    import { AuthService } from '../auth.service';
    import { Router } from '@angular/router';


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

      //email:string = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="73161e121a1f330a121b1c1c5d1501">[email protected]</a>'; 
      //password:string = 'password'; // it connect when i initialize the var's

      constructor(private authService: AuthService, private router:Router) { }

      ngOnInit() {
      }

      seConnecter(email,password)
      {
        this.authService.signInUser(email,password).then(
          () => {
            alert('Welcome '+ email);
            this.router.navigate(['']);
          },
          (error) => {
            console.log('Connection Problem '+error);
            alert('Account inaccessible');
          }
        );
      }
    }

component.html

<div class="container">
    <h1>
        log-In
    </h1>
    <form>
      <div class="form-group">
        <label for="name">E-mail :</label>
        <input type="email" class="form-control" required id="email" #email>
      </div>

      <div class="form-group">
        <label for="alterEgo">Password :</label>
        <input type="password" class="form-control" required id="password" #password>
      </div>

      <button type="submit" class="btn btn-success" (click)='seConnecter(email,password)'>Submit</button>

    </form>
</div>

Answer №1

Ensure that your elements are being passed to your method(seConnecter). Adjust your html markup as shown below:

  <button type="submit" class="btn btn-success" (click)='seConnecter(email.value,password.value)'>Submit</button>

To Edit :

Create a model :

export interface LoginModel {
  email: string;
  password: string;
}

Your updated html :

<form (submit)="seConnecter($event)">
  <div class="form-group">
    <label for="name">E-mail :</label>
    <input type="email" class="form-control" required #email="ngModel" [(ngModel)]="this.model.email" />
  </div>
  <div class="form-group">
    <label for="alterEgo">Password :</label>
    <input type="text" class="form-control" required #password="ngModel" [(ngModel)]="this.model.password" />
  </div>
  <div class="form-group">
    <input type="submit" value="submit" />
  </div>
</form>

TypeScript code:

  seConnecter(event: Event) {
    event.preventDefault();
    this.authService.signInUser(this.model.email, this.model.password).then(
      () => {
        alert('Welcome ' + this.model.email);
        this.router.navigate(['']);
      },
      (error) => {
        console.log('Connection Problem ' + error);
        alert('Account inaccessible');
      }
    );
  }

Alternatively, you can change the type of your button element to "button" instead of "submit" in accordance with your query:

<form>
  <div class="form-group">
    <label for="name">E-mail :</label>
    <input type="email" class="form-control" required id="email" #email>
  </div>

  <div class="form-group">
    <label for="alterEgo">Password :</label>
    <input type="password" class="form-control" required id="password" #password>
  </div>
  <button type="button" class="btn btn-success" (click)='seConnecter(email.value,password.value)'>Submit</button>
</form>

TypeScript code:

  seConnecter(email: string,password: string)
  { 
     ...
  }

Answer №2

It seems like the issue you're facing is that seConnecter() function is missing the correct parameters:

Here's the corrected version:

 seConnecter(email, password)
 {
 this.authService.signInUser(email,password).then(
  () => {
    alert('Welcome '+ email);
    this.router.navigate(['']);
  },
    (error) => {
       console.log('Connection Problem '+error);
       alert('Account inaccessible');
      }
    );
 }

Answer №3

When opting for a template form, you can easily obtain the form value without creating any additional properties at the component level. This is essentially the essence of template forms, whereas reactive forms offer an alternative approach.

Template Form

<div class="container">
    <h1>
        Log-In
    </h1>
    <form #loginForm="ngForm" (ngSubmit)="seConnecter(loginForm.value)">
      <div class="form-group">
        <label for="name">E-mail :</label>
        <input type="email" class="form-control" required id="email">
      </div>

      <div class="form-group">
        <label for="alterEgo">Password :</label>
        <input type="password" class="form-control" required id="password" >
      </div>

      <button type="submit" class="btn btn-success">Submit</button>
    </form>
</div>

In order to utilize form control in the form, you need to incorporate ngModel directive and assign a name to it.

You have the option to disable the submit button until the form is valid based on the configured validation settings.

<button type="submit" class="btn btn-success" [disabled]="loginForm?.form.invalid" >
     Submit
 </button>

Component

  seConnecter(formValue) {
    const {email , password} = formValue;
    ....
  }

Live Demo 🚀

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

Looping through the json resulted in receiving a null value

When working with typescript/javascript, I encountered an issue while trying to fetch the 'statute' from a data object: {_id: "31ad2", x: 21.29, y: -157.81, law: "290-11",....} I attempted to assign data.law to a variable, but received a typeer ...

What could be causing my TypeScript object to appear as "undefined" when I try to log it?

I created a StackBlitz demo featuring a button that, when clicked, should pass a value to the controller. In the controller, there is a function designed to assign this value to an object. However, TypeScript seems to be indicating that the object is undef ...

Is there an alternative method to incorporate the 'environment.ts' file into a JSON file?

In my Angular application, I need to import assets based on the env configuration. I am attempting to extract the patch information from environment.ts and save it into my assets as a json file. However, I am unsure of the proper method to accomplish this. ...

How to Route in Angular 5 and Pass a String as a Parameter in the URL

I am currently working on an Angular project that focuses on geographic system data. The concept is as follows: I have a component with the route: {path: 'home'}. I aim to pass a geojson URL along with this route, making it look like this: {pat ...

The state of dynamically created Angular components is not being preserved

My current task involves dynamically creating multiple components to be placed in a table. The code successfully achieves this objective, but the state seems to be getting jumbled up at the level of the dynamically generated components. When a component is ...

How do @material-ui/core and @types/material-ui interact with each other?

Exploring a sample project that utilizes material-ui. Upon inspecting the package.json file, I noticed the inclusion of the following packages: { ... "dependencies": { "@material-ui/core": "^1.4.1", ... }, "devDependencies": { "@types ...

Type arguments cannot be accepted in untyped function calls.ts(2347)

My user schema in typescript includes the following interface: interface IUser{ name: string; email: string; password: string; isAdmin: boolean; } Check out the user schema below: const UserSchema = new Schema<IUser>( { name: { type ...

Encountered an error with NEXT JS: npm ERR! - error code ERR_SOCKET

npm ERR! code ERR_SOCKET_TIMEOUT npm ERR! network Socket timeout npm ERR! network This issue is related to problems with your network connectivity. npm ERR! network Typically, being behind a proxy or having incorrect network settings can cause this error. ...

Tips for creating a default route with parameters in Angular Component Router?

I am trying to set a default route in my sub-component (using useAsDefault: true) and have parameters automatically passed to it, but I can't seem to find any information on how to accomplish this in the documentation. I have a parent component with t ...

What are the differences between Angular directives with and without square brackets?

I came across an interesting tutorial that showcases the implementation of a tooltip directive in Angular: CASE A: Tooltip without brackets <p tooltip="Tooltip from text">Tooltip from text</p> CASE B: Tooltip with brackets <p [toolt ...

Creating a Typescript interface for a anonymous function being passed into a React component

I have been exploring the use of Typescript in conjunction with React functional components, particularly when utilizing a Bootstrap modal component. I encountered some confusion regarding how to properly define the Typescript interface for the component w ...

Issue: Prior to initiating a Saga, it is imperative to attach the Saga middleware to the Store using applyMiddleware function

I created a basic counter app and attempted to enhance it by adding a saga middleware to log actions. Although the structure of the app is simple, I believe it has a nice organizational layout. However, upon adding the middleware, an error occurred: redu ...

Ways to invoke main.ts to communicate with an Angular component using Electron

I have a good understanding of how to communicate between an angular app and the electron main thread using IPC. However, in my current scenario, I have threads running in the electron main thread for video processing. After these threads complete their t ...

Selecting a radio button by clicking on its corresponding label within an Angular Material dialog

I recently implemented a custom rating bar in Angular, which worked perfectly fine in a basic component. However, when I tried to move it to a MatDialog component, I encountered some issues. In the initial setup, my input was set to display: none so that t ...

The sole coding platform that fails to acknowledge the "ng" command is Visual Studio Code

Many users have encountered issues where the computer does not recognize 'ng,' but my problem differs from that. Interestingly, every software with a command shell recognizes 'ng' except for VS Code. IntelliJ? Works fine. Git bash? N ...

Encountering a CORS issue while attempting to make a GET request to an API in an

Looking to retrieve HTML data from a website using an API. The target URL is: https://www.linkedin.com/ Trying to fetch the HTML page as text from this specific URL. Here's what I attempted: getData() { const api = "https://www.linkedin. ...

Developing a Gulp buildchain: Transforming Typescript with Babelify, Browserify, and Uglify

I've configured a buildchain in Gulp, but when I execute the gulp command, it only utilizes one of the two entry points I specify. My goal is to merge the methods outlined in these two resources: and here: https://gist.github.com/frasaleksander/4f7b ...

Is there a way to efficiently convert several strings within an object that has been retrieved from an HTTP request into another language, and subsequently save this object with the

Is there a way for me to translate some strings in an object before storing it in another http request using the Google Translate API? I am currently getting the object from one http request and saving it with a put method. How can this be achieved? servi ...

Troubleshooting issue with loading local json files in Ionic 3 on Android device

Recently, I've been exploring the process of loading a local JSON data file in my project. I have stored my .json files in the /src/assets/data directory and here is the provider code snippet that I am utilizing: import { Injectable } from '@ang ...

Error message in Angular 2 RC-4: "Type 'FormGroup' is not compatible with type 'typeof FormGroup'"

I'm currently facing an issue with Angular 2 forms. I have successfully implemented a few forms in my project, but when trying to add this one, I encounter an error from my Angular CLI: Type 'FormGroup' is not assignable to type 'typeo ...