Home > Software design >  Store input data into an array [Angular 14]
Store input data into an array [Angular 14]

Time:08-15

I am trying to store input data to users.service.ts component when user enters their email and password. I've made dummy array and I basically want input to be stored within the users component.

HTML:

<div>
    <div *ngIf="displaySignUp" id="signup">
      <h1>Sign Up for Free</h1>

      <form>
        <div >
          <div >
            <input
              type="text"
              placeholder="First Name*"
              required
              autocomplete="off"
            />
          </div>

          <div >
            <input
              type="text"
              placeholder="Last Name*"
              required
              autocomplete="off"
            />
          </div>
        </div>

        <div >
          <input
            type="email"
            placeholder="Email Address*"
            required
            autocomplete="off"
          />
        </div>

Log in component:

import { Component, OnInit } from '@angular/core';

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

  ngOnInit(): void {}

  displaySignUp: any;
  displayLogIn: any;
  displayFrogotPassword: any;

  fname: any;
  lname: any;
  email: any;
  password: any;

  displayHeader(option: string) {
    if (option == 'signUp') {
      this.displaySignUp = true;
      this.displayLogIn = false;
      this.displayFrogotPassword = false;
    } else {
      this.displaySignUp = false;
      this.displayLogIn = true;
      this.displayFrogotPassword = false;
    }
  }
}

Users component where I want to store data:

export class UserService {
  constructor() {}

  users = [
    {
      fname: 'first',
      lname: 'last',
      email: '[email protected]',
      password: 'temp12345',
    },
    {
      fname: 'first2',
      lname: 'last2',
      email: '[email protected]',
      password: 'abc12345',
    },
  ];
}

Thank you in advance!

CodePudding user response:

inject UserService into LoginComponent and when user enter it's user name end password - simply call this.userService.users.push({ email: 'from input', password: 'from input',})

CodePudding user response:

if i see your code , that make me feel that you have not read about the forms in angular. angular provides us two methods to handle the forms , the first is called template-driven forms and the second called the reactive forms. i advice you to use one of them to build your form , this is a good article talking about creating forms in angular : https://xpertuto.com/using-angular-formbuilder-and-formgroup/

now i will go back to your code and update it to make it more reactive. first you need to :

1- import formBuilder class to your component to use the formGroup

import {Component, OnInit } from '@angular/core';
import {FormBuilder} from "@angular/forms";

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

  constructor(private formBuilder: FormBuilder) {
  }

2- import reactiveFormBuilder in you appModule

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { LoginComponent } from './app.component';
import {ReactiveFormsModule} from "@angular/forms";

@NgModule({
  declarations: [
    LoginComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [LoginComponent]
})
export class AppModule { }

3- now you need to create your fromGroup using the formBuilder

loginForm : FormGroup;
   
  ngOnInit() {
    this.loginForm = new FormGroup({
      'fname': new FormControl( ),
      'lname': new FormControl(),
      'email': new FormControl()
    })

    this.formBuilder.group(this.loginForm);
  }

4- you need to update your html to apply the form

  <form [formGroup]="loginForm">
      <div >
        <div >
          <input
            formControlName="fname"
            type="text"
            placeholder="First Name*"
            required
            autocomplete="off"
          />
        </div>

        <div >
          <input
            formControlName="lname"
            type="text"
            placeholder="Last Name*"
            required
            autocomplete="off"
          />
        </div>
      </div>

      <div >
        <input
          formControlName="email"
          type="email"
          placeholder="Email Address*"
          required
          autocomplete="off"
        />
      </div>
      <button (click)="submit()" [disabled]="!loginForm.valid">Submit</button>
    </form>
    
  </div>

5- now if i see ,when you click the submit button you want to pass the data to UserService , so you need to inject your service in your constructor first and we use it when we submit the form.

    constructor(private userService: UserService) {
      }
    

  submit(): void {   
  const loginData = this.loginForm.getRawValue();
  // it could be an observable and get the response
  this.userService.useData(loginData);
  }

6- finally , update the userService and add the new function accepting the formData , then you could call an API or do what you need with data.

export class UserService {
  constructor() {}
  
  useData(formData: any) :void{
  // do what you need with formData
 }
}
  • Related