Angular 2 Passing form data to another component - javascript

I have a form which allows user to create an account, once the user clicks on submit button the user is navigated to another page with the details of that account they have create. The issue I am having is passing that object to the details view.
For example here is my component for the form,
import {Component, OnInit, OnDestroy, Input} from '#angular/core';
import { FormGroup, FormBuilder, Validators } from '#angular/forms';
import {Customer} from "../model/customer";
import {Router } from '#angular/router';
import {CustomerService} from "../service/customer.service";
import {CustomerProfileComponent} from "../customer-profile/customer-profile.component";
#Component({
selector: 'app-new-customer',
templateUrl: './new-customer.component.html',
styleUrls: ['./new-customer.component.css']
})
export class NewCustomerComponent implements OnInit {
#Input() customer: Customer;
//this is only dev data do not use this in prod
private countries = [];
private customerSources = [];
private secondarySources =[];
//Create the forum group
public newCustomerForm: FormGroup;
public submitted: boolean; // keep track on whether form is submitted
constructor(private fb: FormBuilder, public customerService: CustomerService,private router: Router) {
this.countries = [
{value:'UK'},
{value:'Germany'},
{value:'Turkey'},
{value:'Italy'}
];
this.customerSources = [
{value: 'Through a friend or colleague (not a Client)'},
{value: 'Through an existing Client'},
{value: 'Direct Sales (e.g. cold call, direct mail, email)'},
{value: 'Web Search e.g. Google'}
];
this.secondarySources = [
{value: '1st Hire'},
{value: 'A Test Client With A Long Business Name'},
{value: 'Abbigail West'}
];
}
ngOnInit() {
this.newCustomerForm = this.fb.group({
id:[''],
company_name: ['', [<any>Validators.required, <any>Validators.minLength(5)]],
vat:[''],
address:[''],
country:[''],
first_name:[''],
surname:[''],
phone:[''],
email:['',[<any>Validators.required, <any>Validators.minLength(5)]],
customer_sources:[''],
secondary_sources:['']
});
}
here is my form html,
<form [formGroup]="newCustomerForm" novalidate (ngSubmit)="saveNewCustomer(newCustomerForm.value, newCustomerForm.valid)">
<section>
<aside>
<p>Once you've added your new <b>Client</b>, you can come back and allow them access to view their <b>Invoices</b> & <b>Payments</b> - they can also make <b>Payments</b> via Paypal if you have it enabled.</p>
</aside>
<input type="hidden" name="id" formControlName="id"/>
<h4>New Client Details</h4>
<md-input-container>
<input mdInput type="text" name="company_name" placeholder="Customer Name" formControlName="company_name" />
<small [hidden]="newCustomerForm.controls.company_name.valid || (newCustomerForm.controls.company_name.pristine && !submitted)">
Customer Name is required (minimum 5 characters).
</small>
</md-input-container>
<md-input-container>
<input mdInput type="text" name="vat" placeholder="VAT Number" formControlName="vat"/>
</md-input-container>
<md-input-container>
<input mdInput type="text" name="address" placeholder="Address" formControlName="address" />
</md-input-container>
<md-select placeholder="Country" name="country" formControlName="country" >
<md-option *ngFor="let country of countries" [value]="country.value" >
{{country.value}}
</md-option>
</md-select>
<h4>Your Primary Contact</h4>
<div class="left-column">
<md-input-container>
<input mdInput type="text" name="first_name" placeholder="First Name" formControlName="first_name" />
</md-input-container>
</div>
<div class="left-column">
<md-input-container>
<input mdInput type="text" name="surname" placeholder="surname" formControlName="surname" />
</md-input-container>
</div>
<div class="clearfix"></div>
<div class="left-column">
<div class="left-column">
<md-input-container>
<input mdInput type="text" name="phone" placeholder="Phone" formControlName="phone"/>
</md-input-container>
</div>
</div>
<div class="right-column">
<div class="left-column">
<md-input-container>
<input mdInput type="text" name="email" placeholder="Email" formControlName="email"/>
<small [hidden]="newCustomerForm.controls.email.valid || (newCustomerForm.controls.email.pristine && !submitted)">
Email is required (minimum 5 characters).
</small>
</md-input-container>
</div>
</div>
<div class="clearfix"></div>
<h4>Customer Source</h4>
<div class="left-column">
<md-select placeholder="How were you introduced to this Client?" formControlName="customer_sources">
<md-option *ngFor="let cs of customerSources" [value]="cs.value" >
{{cs.value}}
</md-option>
</md-select>
</div>
<div class="right-column">
<md-select placeholder="Which Client introduced you?" formControlName="secondary_sources">
<md-option *ngFor="let ss of secondarySources" [value]="ss.value" >
{{ss.value}}
</md-option>
</md-select>
</div>
<div class="clearfix"></div>
</section>
<aside>
<div class="right-aside">
<button type="submit" class="cancel">Cancel</button>
<button type="submit" class="save">Save</button>
</div>
<div class="clearfix"></div>
</aside>
</form>
Customer service is in my app.module. Here I am saving the data and moving the user on to the new page.
saveNewCustomer(customer: Customer, isValid: boolean){
if(isValid){
this.submitted = true; // set form submit to true
this.customerService.saveNewCustomer(customer)
.subscribe(
res => this.customer,
error => console.log(<any>error)
);
this.router.navigateByUrl('/earning/customers/profile');
}
}
}
And this is the component I would like the customer object to use so it be present in the view.
import {Component, OnInit, Input} from '#angular/core';
import {Customer} from "../model/customer";
import {NewCustomerComponent} from "../new-customer/new-customer.component";
#Component({
selector: 'app-customer-profile',
templateUrl: './customer-profile.component.html',
styleUrls: ['./customer-profile.component.css'],
providers:[NewCustomerComponent]
})
export class CustomerProfileComponent implements OnInit {
#Input() customer: Customer;
constructor() {
console.log(this.customer);
}
ngOnInit() {
}
}
<main>
<header>
<h4> </h4>
<h1><strong><i></i>Customer profile</strong></h1>
</header>
<article>
<section>
<p></p>
<p>
{{customer}}
</p>
</section>
</article>
</main>
But customer is undefined in the CustomerProfileComponent. I am not sure what I am doing wrong. if anyone can point me in the right direction would be much appreciated.
Update to include service class based on suggestion
import { Injectable } from '#angular/core';
import {Http, Response, Headers, RequestOptions} from '#angular/http';
import {CookieService} from "angular2-cookie/services/cookies.service";
import {Observable, Subject} from "rxjs";
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import {Customer} from "../model/customer";
#Injectable()
export class CustomerService {
private csrfToken;
private newCustomerUrl = "/earning/customers/new";
private customer = new Subject<Object>();
customer$ = this.customer.asObservable();
constructor(public http: Http, private cookieService: CookieService) {
this.getCsrfToken();
}
getCsrfToken(){
this.csrfToken = this.cookieService.get("PLAY_SESSION").substring(this.cookieService.get("PLAY_SESSION").indexOf("csrfToken"));
}
saveNewCustomer(customer:Customer): Observable<Customer>{
let headers = new Headers({
'Content-Type':'application/json'
});
let options = new RequestOptions({ headers: headers });
return this.http.post(this.newCustomerUrl+"?"+this.csrfToken, customer, options) // ...using post request
.map((res:Response) => res.json()) // ...and calling .json() on the response to return data
.catch(this.handleError); //...errors if any
}
private handleError (error: Response) {
return Observable.throw('Internal server error: ' + error);
}
emitCustomer(customer) {
this.customer.next(customer);
}
}

As mentioned a shared service would be a good option. the following example is sharing the Object between the components via service:
Your service:
public sharedCustomer = {};
And the component, after that you have received your customer from the api, push the customer to the service:
this.customerService.saveNewCustomer(customer)
.subscribe(res => {
this.customer = res;
this.customerService.sharedCustomer = this.customer;
this.router.navigateByUrl('/earning/customers/profile');
});
}
Notice that I'm emitting the customer inside the subscription, as well as the navigation, to ensure that the customer gets stored in the service properly, as well as not navigating away from page before that.
Then in your detail page:
ngOnInit() {
this.customer = this.customerService.sharedCustomer;
}

Related

Trying to add post

I was trying to add post for a college project but somehow it reloads the page and resets the page. It does not show the post. I tried to submit the form through the add post but it doesn't work.
I'm fairly new to angular so i don't know what to do. Please help me
this is my post.component.html
<h3>Add Post</h3>
<form (formGroup)="form" (ngSubmit)="submit()">
<div class="form-group">
<label for="title">Title</label>
<input
formControlName="title"
id="title"
type="text"
(ngModel)="posts.title"
class="form-control"
required/>
</div>
<div class="form-group">
<label for="body">Body</label>
<input
formControlName="body"
id="body"
type="text"
(ngModel)="posts.body"
class="form-control"
required/>
</div>
<div class="form-group">
<button
class="btn btn-primary"
type="submit">Add Posts</button>
</div>
</form>
this is my post.component.ts for reference
import { Component, OnInit } from '#angular/core';
import { Post } from './post.model';
import { PostService } from './post.service';
import { FormGroup } from '#angular/forms'
import { ActivatedRoute, Router } from '#angular/router';
import { Subscription } from 'rxjs';
#Component({
selector: 'app-post',
templateUrl: './post.component.html',
styleUrls: ['./post.component.css']
})
export class PostComponent implements OnInit, OnDestroy {
id: number;
form: FormGroup;
posts: Post;
post: Post[] = [];
constructor(
public postService: PostService,
private route: ActivatedRoute,
private router: Router) { }
ngOnInit(): void {
this.postService.getAll().subscribe((data: Post[])=>{
this.post = data;
console.log(this.post);
})
}
submit(){
console.log(this.form.value);
this.postService.update(this.id, this.form.value).subscribe(res => {
console.log('Post updated successfully!');
})
}
}
don't use reactive form and template driven from same time.
Which means if you are using formControlName don't use ngModel or vice versa.
<h3>Add Post</h3>
<form>
<div class="form-group">
<label for="title">Title</label>
<input
id="title"
type="text"
name="title"
[(ngModel)]="posts.title"
class="form-control"
required/>
</div>
<div class="form-group">
<label for="body">Body</label>
<input
id="body"
type="text"
name="body"
[(ngModel)]="posts.body"
class="form-control"
required/>
</div>
<div class="form-group">
<button
class="btn btn-primary"
type="button" (click)="submit()">Add Posts</button>
</div>
</form>
import { Component, OnInit, VERSION } from '#angular/core';
import { FormGroup } from '#angular/forms';
import { ActivatedRoute, Router } from '#angular/router';
#Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
id: number;
form: FormGroup;
posts = { title: '', body: ''};
post = [];
constructor(
public postService: PostService,
private route: ActivatedRoute,
private router: Router
) { }
ngOnInit(): void {
this.postService.getAll().subscribe((data)=>{
this.post = data;
console.log(this.post);
})
}
submit(){
console.log(this.posts);
this.postService.update(this.id, this.posts).subscribe(res => {
console.log('Post updated successfully!');
})
}
}
Please follow the changes made in below link. Here I have used template driven form.
https://stackblitz.com/edit/angular-ivy-nnphce?file=src%2Fapp%2Fapp.component.html

Property 'title' does not exist on type '{}'

Angular
In the first few tags I have an input tag input #title = "ngModel" [(ngModel)]="product.title" this code where I am trying to use two way binding to be able to edit my form and values that I get from the firebase database. I created an empty product object in product-form.component.ts but I get the property type error. I am not sure why the empty product object causing error because the tutorial I'm watching has the same approach. Goal is to be able to use that empty product object or an alternate approach to be able to work with two way binding
product-form.component.ts
import { ProductService } from './../../product.service';
import { CategoryService } from './../../category.service';
import { Component, OnInit } from '#angular/core';
import { Router, ActivatedRoute } from '#angular/router';
import { take } from 'rxjs/operators';
#Component({
selector: 'app-product-form',
templateUrl: './product-form.component.html',
styleUrls: ['./product-form.component.css']
})
export class ProductFormComponent implements OnInit {
categories$;
product = {};
constructor(
private route: ActivatedRoute,
private router: Router,
private categoryService: CategoryService,
private productService: ProductService)
{
this.categories$ = categoryService.getCategories();
let id = this.route.snapshot.paramMap.get('id');
if (id) this.productService.get(id).pipe(take(1)).subscribe(p => this.product = p);
}
save(product){
this.productService.create(product);
this.router.navigate(['/admin/products']);
}
ngOnInit(): void {
}
}
product-form.html
<div class="row">
<div class="col-md-6">
<form #f = "ngForm" (ngSubmit) = "save(f.value)">
<div class="form-group">
<label for="title">Title</label>
<input #title = "ngModel" [(ngModel)]="product.title" name = "title" id = "title" type="text" class="form-control" required>
<div class="alert alert-danger" *ngIf = "title.touched && title.invalid">
Title is required
</div>
</div>
<div class="form-group">
<label for="price">Price</label>
<div class="input-group">
<span class="input-group-text">$</span>
<input #price="ngModel" ngModel name ="price" id = "price" type="number" class="form-control" required>
</div>
<div class="alert alert-danger" *ngIf="price.touched && price.invalid">
<div *ngIf="price.errors.required">Price is required.</div>
<div *ngIf="price.errors.min">Price should be 0.</div>
</div>
</div>
<div class="form-group">
<label for="category">Category</label>
<select #category="ngModel" ngModel name="category" id = "category" type="text" class="form-control" required>
<option value=""></option>
<option *ngFor = "let c of categories$ | async" [value] = "c.name">
{{c.name}}
</option>
</select>
<div class="alert alert-danger" *ngIf = "category.touched && category.invalid">
Category is required.
</div>
</div>
<div class="form-group">
<label for="imageUrl">Image Url</label>
<input #imageUrl="ngModel" ngModel name= "imageUrl" id = "imageUrl" type="url" class="form-control" required>
<div class="alert alert-danger" *ngIf = "imageUrl.touched && imageUrl.invalid">
<div *ngIf = "imageUrl.errors.required">Image URL is required.</div>
<div *ngIf = "imageUrl.errors.url">Invalid URL</div>
</div>
</div>
<button class="btn btn-primary">Save</button>
</form>
</div>
<div class="col-md-6">
<div class="card" style="width: 18rem;">
<img [src]="imageUrl.value" class="card-img-top">
<div class="card-body">
<h5 class="card-title">{{title.value}}</h5>
<p class="card-text">{{price.value | currency:'USD':true}}</p>
</div>
</div>
</div>
</div>
product.service.ts
import { Injectable } from '#angular/core';
import { AngularFireDatabase } from '#angular/fire/database';
#Injectable({
providedIn: 'root'
})
export class ProductService {
constructor(private db: AngularFireDatabase) { }
create(product){
return this.db.list('/products').push(product);
// const itemsRef = this.db.list('products');
// return itemsRef.push(product);
}
getAll() {
return this.db.list('/products').valueChanges();
}
get(productId){
return this.db.object('/products/' + productId).valueChanges();
}
}
There are 2 ways to do this
Approach 1
Declare an interface
export interface Product {
title: string
}
Change the Component code section as follows
from
product = {};
To
product:Product;
Approach 2 - This can have side effects
Change HTML
From
<input #title = "ngModel" [(ngModel)]="product.title" name = "title" id = "title" type="text" class="form-control" required>
To
<input #title = "ngModel" [(ngModel)]="product['title']" name = "title" id = "title" type="text" class="form-control" required>
I fixed this error by changing a couple of things in 'tsconfig.json' file.
First remove "strict":true and add instead of it "noImplicitUseStrict":true
(Don't forget adding the comma)

ERROR Error: Cannot find control with path:

I am leveraging Angular 4's FormBuilder and FormGroup class to create a Form. The form's content is supplied by a GET call with the Questions and Answers structured via JSON format.
Dabbling with my localhost, I see the following error from my web console on page load:
Could anyone with Angular Forms expertise correct this implementation and explain where I went wrong?
Web Console indicates this node from the HTML is causing it:
<fieldset [formGroupName]="i">
For sake of brevity, I'm just providing the bare-bone snippets only down below. Let me know if you need more details.
HTML component:
<form id="form-clinicalscreener" [formGroup]="clinicalForm" (submit)="submitScreenerForm(clinicalForm)" novalidate>
<div formArrayName="Questions">
<div class="section" *ngFor="let tab of clinicalQuestionsResults; let i = index;">
<h2 class="form-title">{{tab.DisplayText}}</h2>
<div>
<div class="form-group" *ngFor="let question of tab.Questions">
<fieldset [formGroupName]="i">
<label>{{question.DisplayText}}</label>
<input type="hidden" formControlName="QuestionId" value="{{question.Id}}" data-value="{{question.Id}}">
<div [ngSwitch]="question.AnswerType">
<div *ngSwitchCase="'Radio'" class="form-group-answers">
<div class="radio" *ngFor="let answer of question.Answers">
<input type="radio"
formControlName="AnswerId"
value="{{answer.Id}}"
data-value="{{answer.Id}}"
class="radio-clinicalscreener">
<label class="label-answer">
<span class="label-answer-text">{{answer.DisplayText}}</span>
</label>
</div>
</div>
<div *ngSwitchCase="'DropDown'" class="form-group-answers">
<select formControlName="AnswerId" class="form-control">
<option value="{{answer.Id}}" data-value="{{answer.Id}}" *ngFor="let answer of question.Answers">{{answer.DisplayText}}</option>
</select>
</div>
</div>
</fieldset>
</div>
</div>
</div>
</div>
<div class="text-center">
<button class="btn btn-screener" type="submit" [disabled]="!clinicalForm.valid">Submit</button>
</div>
TypeScript component:
import { Component, OnInit } from '#angular/core';
import { FormGroup, FormBuilder } from '#angular/forms';
#Component({
selector: '',
templateUrl: '',
styleUrls: ['']
})
export class FormComponent implements OnInit {
// Our model driven form.
clinicalForm: FormGroup;
// Screener Data from API call to be used by view in for loop.
clinicalQuestionsResults: any;
constructor(private formBuilder: FormBuilder) {}
ngOnInit() {
// Let's get Clinical Screener metadata.
this.loadClinicalScreener();
// Initialize the form here.
this.clinicalForm = this.formBuilder.group({
Questions: this.formBuilder.array([
this.initQuestions()
])
});
}
private initQuestions() {
// initialize our Questions
return this.formBuilder.group({
QuestionId: [''],
AnswerId: ['']
});
}
private loadClinicalScreener() {
// An AJAX call from a forkJoin() to return the JSON payload, then I assign it to a local object, screenerResponse.
let screenerResponse: any = data[0];
this.clinicalQuestionsResults = screenerResponse.Result.Tabs;
console.log('Here is the metadata for Clinical Screener --->', this.clinicalQuestionsResults);
}
}

Angular Forms - What is the correct way to initialize

I have a basic form that I have built with 3 fields. Name, description and id. The data is meant to be populated by a service that calls out to a C# API that returns JSON that is then loaded to the form.
When it opens I get the correct data but I get this error. If I striped out the name input, the errors just move to the description field then the id.
I am still learning Angular, but have read a heap to try and fix this. I think I've got it all right, but I'm guessing it's something to do with initialisation because if I add this code before getting the data from the scenario service, the errors go.
this.scenario = { 'id': 0,
'name': '',
'description': '',
'dateCreated': '',
'createdBy': '',
'dateModified': '',
'modifiedBy': '',
'active': true };
So what is the correct way to code this so my interface is initialised without having to hard code it?
test.component.html
<h1>
Edit Scenario - {{ name.value }}
</h1>
<div class='panel-body'>
<form novalidate
#scenarioForm="ngForm"
(ngSubmit)="saveForm()">
<div class='row'>
<div class='col-md-1'><label for="scenarioName" class="control-label">Name</label></div>
<div class='col-md-6'>
<div class="form-group" [class.has-error]="name.invalid && name.touched">
<input class="form-control"
#name="ngModel"
name="scenarioName"
type="text" maxlength="50" placeholder="Scenario name" required
[(ngModel)]="scenario.name">
</div>
</div>
</div>
<div class='row'>
<div class='col-md-1'><label for="descption">Descption</label></div>
<div class='col-md-6'>
<div class="form-group" [class.has-error]="description.invalid && description.touched">
<textarea #description="ngModel"
ngControl="description"
class="form-control"
rows="4" maxlength="500"
placeholder="What is this scenario for?"
required
name="description"
[(ngModel)]="scenario.description"></textarea>
<div *ngIf="description.invalid && description.dirty" class="alert alert-danger">
Description is required, and must be at least blah blah...
</div>
</div>
</div>
</div>
<div class='panel-footer'>
<button class="btn btn-default" type="submit">Save</button>
</div>
<br><br>
<input #id type="text" name="id" [(ngModel)]="scenario.id" #id="ngModel">
</form>
<div id="debugging">
<br>
Valid? {{scenarioForm.valid}}<br>
Model: {{ scenario | json }} <br>
Model: {{ result | json }}<br>
Form: {{ scenarioForm.value | json }}
<br>
</div>
test.component.ts
import { Component, OnInit, NgModule } from '#angular/core';
import { SharedModule } from './../shared/shared.module';
import { FormsModule, NgForm, FormGroup } from '#angular/forms';
import { CommonModule } from '#angular/common';
import { ScenarioService } from './scenario.service';
import { IScenario } from './scenario';
import { Router, ActivatedRoute } from '#angular/router';
#NgModule({
imports: [
FormsModule
],
exports: [FormsModule]
})
#Component({
selector: 'app-scenario-form',
templateUrl: './test.component.html',
})
export class TestComponent implements OnInit {
// tslint:disable-next-line:no-inferrable-types
private pageTitle: string = 'New Scenario';
scenario: IScenario;
result: IScenario;
constructor(private _scenarioService: ScenarioService,
private _route: ActivatedRoute) {}
ngOnInit() {
const scenarioId = this._route.snapshot.paramMap.get('id');
if (scenarioId) {
this._scenarioService.getScenario(+scenarioId).subscribe(
scenario => this.scenario = scenario);
}
}
}
Since you are getting the response from API asynchronously, you need to handle the null initially, you can do that with safe navigation operator
<input #id type="text" name="id" [(ngModel)]="scenario?.id" #id="ngModel">
same applies for all your fields.
As you mentioned above, other way is to fix via initializing the object Scenario
Since you need to accomplish two way data binding, you need to initialize the object by creating an instance
scenario: IScenarioUpdate = {modifiedBy: ''}

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;
});
....
}

Categories

Resources