简体   繁体   中英

how to get value from html form and pass is to typescript in angular

Do anyone know how can I get value from HTML forms in typescript?

this is how my html page: login.component.html

<form [formGroup]="loginForm" id="loginForm" (ngSubmit)="authUser()" #userForm="ngForm">
<div class="container">
  <div class="row">
    <div class="col-sm-6 col-sm-offset-3">
      <p><input type="email" formControlName="email" id="email" placeholder="Your email" [(ngModel)]="user.email" required></p>
    </div>
  </div>
  <div class="row">
    <div class="col-sm-6 col-sm-offset-3">
      <p><input type="password" formControlName="password" id="password" placeholder="Your password" [(ngModel)]="user.password" required></p>
    </div>
  </div>
   <div class="row">
    <div class="col-sm-6 col-sm-offset-3">
      <p><button class="btn btn-primary" type="submit" [disabled]="!bookForm.form.valid">Login</button> </p>    
    </div>
  </div>
 </div>
</form>
<div *ngIf="edited" class="alert alert-success box-msg" role="alert">
        <strong>Successful Login!</strong>
</div>

and this is my typescript: login.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import { Http } from '@angular/http';
import { PostsService } from '../posts.service';
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  loginForm: FormGroup;
  login = false;
  users: any;

  user = {};
  constructor(private fb: FormBuilder, private http: Http, private router: Router, private postsService: PostsService) {
    this.postsService.getAllPosts().subscribe(users => {
      this.users = users;
    });

  }

  ngOnInit() {
    this.loginForm = this.fb.group({
      email: 'a@b.com',
      password: 'abc123.'

    });
  }
  authUser() {
    var i:number;
    var email:string = this.loginForm.value.email;
    var password:string = this.loginForm.value.password;
    var userType:string;
    var userEmail:string;
    for(i=0;i<this.users.length;i++){
      if(this.users[i].email == email && this.users[i].password == password){
         this.login = true
         userEmail = this.users[i].email;
         userType = this.users[i].accountType;
        }
    }
    if(this.login){
      console.log("Sucessful");
    }
    else{
      console.log("Unsucessful");

    }
  }

}

I have tried a lot of methods but none of them seems to work for now my login the way my code words is that once the button is press it will not check whats in the html forms. but it will check againce var email:string = this.loginForm.value.email; and my database for the email and the value thats in var email:string = this.loginForm.value.email; have been hardcoded.

You can try to get value from your ngModel and use .find function to filter your data it's easy and fast to get user details

public userType: string;
public userEmail:string;
public loginUser:any;
authUser() {
    this.loginUser =  this.users.find(x => x.email == this.user.email && x.password == this.user.password);
    if(this.loginUser){
        this.login = true
        this.userEmail = this.loginUser.email;
        this.userType = this.loginUser.accountType;
    }
}

You need the prevent default behavior of form. Use following code in your authUser method:

authUser(event) {
    event.preventDefault();
    //rest of code
  }

and update your form tag:

<form [formGroup]="loginForm" id="loginForm" (ngSubmit)="authUser($event)" #userForm="ngForm">

1.- don't mix Reactive form and Template forms.

//with ReactiveForm
<input type="password" formControlName="password" id="password" placeholder="Your password" >
//with template Drive Form
<input type="password" id="password" placeholder="Your password" [(ngModel)]="user.password" required>

2.- with Template driven Form you must have

this.user:any={
      email: 'a@b.com',
      password: 'abc123.'
}
//And in the submit function you have this.user.email and this.user.password

3.- with Reactive Form

//the validators it's included when create the fbgroup
this.loginForm = this.fb.group({
      email: ['a@b.com',Required]
      password: ['abc123.',Required]

    });
//in the submit pass loginForm as argument
<form [formGroup]="loginForm" id="loginForm" (ngSubmit)="authUser(loginForm)">
//then in your authUser
authUser(form:any){ 
  if (form.valid)
  { 
      console.log(form.value.email,form.value.password)
  }
}

4.-You're checking email and password compared with a list of users, but you really have not a list of users. if really post.Service.getAllPost get a list of users the method have a "very bad" name. Ah! put the subscribe in a ngOnInit, not in de constructor

ngOnInit()
{
this.postsService.getAllPosts().subscribe(users => {
      this.users = users;
    });
    ....
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM