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

NextAuth credentials are undefined and authentication is malfunctioning in React

I encountered the following issue: This is the code snippet that I am using: return ( <> {Object.values(providers).map((provider) => { if (provider.id === "credentials") { return null; } retu ...

Utilizing Node.js Functions for Sharing Database Queries

When it comes to sharing DB query code among multiple Node.js Express controller methods, finding the best practice can be challenging. Many samples available online don't delve deeply into this specific aspect. For instance, let's consider a ge ...

The specified property cannot be found on the object type in a Svelte application when using TypeScript

I am attempting to transfer objects from an array to components. I have followed this approach: https://i.stack.imgur.com/HHI2U.png However, it is indicating that the property titledoes not exist in this type. See here: https://i.stack.imgur.com/VZIIg.pn ...

The issue here pertains to npm's inability to successfully retrieve a required dependency for download

C:\Users\Manoj\Desktop\accounts>npm install intro.js --save npm ERR! code ENOENT npm ERR! syscall spawn git npm ERR! path git npm ERR! errno ENOENT npm ERR! enoent Error while executing: npm ERR! enoent undefined ls-remote -h -t ssh: ...

Assign a value to ReplaySubject if it is currently devoid of any

I am facing a challenge with my ReplaySubject in the component after content initialization. Whenever it initializes, it always gets set to "/api/bulletin/getall" value and overrides any value assigned to it before in the onViewChanged function. How can ...

Retrieve user information by their unique user ID from a MongoDB database using a Node, Express, and TypeScript API

Currently, I am working on a Node JS and Express with TypeScript API project. In this project, I need to retrieve data stored by a specific user from MongoDB based on their user ID. This is a snippet from my DataRouter.ts: router.get('/:userId', ...

Obtain the precise Discriminated conditional unions type in the iterator function with Typescript

export type FILTER_META = | { type: 'string'; key: string; filters: { id: string; label?: string }[]; } | { type: 'time'; key: string; filters: { min: string; max: string }[]; } | { ...

Error TS2304: Unable to locate identifier 'QRScanner'

I am currently exploring https://www.npmjs.com/package/cordova-plugin-qrscanner in order to implement a QR scanning feature in my mobile application. As part of the initial steps, I have written the following code snippet in my typescript file: function o ...

Encountering the following error message: "E11000 duplicate key error collection"

Currently, I am in the process of developing an ecommerce platform using the MERN stack combined with TypeScript. As part of this project, I am working on a feature that allows users to provide reviews for products. The goal is to limit each user to only o ...

Component's mocking service is being ignored

I am currently exploring how to simulate a service (specifically one that makes http calls) in order to test a component. @Component({ selector: 'ub-funding-plan', templateUrl: './funding-plan.component.html', styleUrls: ['. ...

What's the best way to assign a dual-value condition within a form group field?

// Setting up a form group in Angular this.form = this.fb.group({ id:[], name: [ details.name || '' ] }) I am wondering if it is possible to assign a value in the form based on the content of details.name. If details.name has ...

Tips for specifying a variable as a mandatory key attribute within an array

Is there a way to dynamically determine the type of key attribute in an array? const arr = [ { key: 'a' }, { key: 'b' }, { key: 'c' }, ]; type key = ??? // Possible values for key are 'a', 'b', or &a ...

When working with Angular 12, the target environment lacks support for dynamic import() syntax. Therefore, utilizing external type 'module' within a script is not feasible

My current issue involves using dynamic import code to bring in a js library during runtime: export class AuthService { constructor() { import('https://apis.google.com/js/platform.js').then(result => { console.log(resul ...

Angular - Display shows previous and current data values

My Angular application has a variable called modelResponse that gets updated with new values and prints them. However, in the HTML, it also displays all of its old values along with the new ones. I used two-way data binding on modelResponse in the HTML [( ...

Angular 7 router navigate encountering a matching issue

I created a router module with the following configuration: RouterModule.forRoot([ {path: 'general', component: MapComponent}, {path: 'general/:id', component: MapComponent}, {path: '', component: LoginComponent} ]) Sub ...

Coding with Angular 4 in JavaScript

Currently, I am utilizing Angular 4 within Visual Studio Code and am looking to incorporate a JavaScript function into my code. Within the home.component.html file: <html> <body> <button onclick="myFunction()">Click me</button> ...

How does the use of nodejs, a server-side scripting language, tie into ReactJs or other front-end languages?

Can Node, being a server-side scripting language, be effectively utilized in the development of front-end applications such as npx create-react-app or npx create-nuxt-app? ...

Changing an array into an object in JavaScript without rearranging the keys

I have a collection { 1: {id: 1, first: 1, last: 5} 2: {id: 2, first: 6, last: 10} 3: {id: 3, first: 11, last: 15} } My goal is to reverse the order of items without rearranging the keys so that it looks like this: { 1: {id: 3, first: 11, last: 15} 2: { ...

Troubleshooting: Dealing with Cross-Origin Resource Sharing (CORS)

I'm facing an issue with my server.js files. One of them is located inside the backend folder, and when I run nodemon server.js on localhost:3000, everything runs smoothly. I start Angular by running ng serve inside the angular folder, and logging int ...

How can you set a value to a radio button with Angular 4?

How can I set the JSON value for the radio buttons (Unlimited, Custom) below? I tried using [(ngModel)]="user.accessSchedule.fullAccess", but it's not working. <ol-radio-group [selected]="unlimitedAccessSchedule" id="accessSchedule" [(ngModel)]=" ...