I'm trying a user registration form using MEAN, but I keep getting error 500 on passing data to the database.
I tried using save instead of the register, but that doesn't hash the password.
I had this method working on a project without angular, but it's not working here.
If there is an alternative to save the data with a hashed password, that's also helpful.
This is the post code:
app.post('/signup', VerifyToken, (req,res) =>
{
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS");
console.log(req.body);
const errors = validationResult(req);
if (!errors.isEmpty())
{
return res.status(422).jsonp(errors.array());
}
else
{
User = new userData(
{
name: req.body.user.name,
email: req.body.user.email,
blood: req.body.user.blood,
address1: req.body.user.address1,
address2: req.body.user.address2,
});
userData.register(User, req.body.user.password);
}
});
This is the service that sends data:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class UsersService {
constructor(private http:HttpClient) { }
// getUsers()
// {
// return this.http.get('');
// }
newUser(user)
{
return this.http.post('http://localhost:5000/signup',{'user' : user})
.subscribe(data => {console.log(data)});
}
};
And this is the signup component TS code:
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import { UserModel } from './user.model';
import { UsersService } from '../users.service';
#Component({
selector: 'app-signup',
templateUrl: './signup.component.html',
styleUrls: ['./signup.component.css']
})
export class SignupComponent implements OnInit {
constructor(private usersService: UsersService, private router: Router) { }
title: String = "Register as a new Donor here";
userItem = new UserModel(null,null,null,null,null,null);
ngOnInit(): void {
}
AddUser()
{
this.usersService.newUser(this.userItem);
console.log("called");
alert("success");
this.router.navigate(['/']);
}
}
This is the HTML code of the signup component:
<div>
<h4 class="card-header">{{title}}</h4>
</div>
<div class="container formDiv">
<form (ngSubmit)="AddUser()">
<div class="form-group">
<input type="text" class="form-control" id="fullName" name="name" [(ngModel)]="userItem.name" placeholder="Enter Full Name" required>
</div>
<div class="form-group">
<input type="email" class="form-control" id="email" name="email" [(ngModel)]="userItem.email" placeholder="Enter Email address" required>
</div>
<div class="form-group">
<select class="form-control" name="blood" id="bloodType" [(ngModel)]="userItem.blood" required>
<option value="0">Select Blood Type</option>
<option value="A+">A+</option>
<option value="A-">A-</option>
<option value="B+">B+</option>
<option value="B-">B-</option>
<option value="O+">O+</option>
<option value="O-">O-</option>
<option value="AB+">AB+</option>
<option value="AB-">AB-</option>
<option value="Bombay">Bombay Blood group</option>
</select>
</div>
<div class="form-group">
<input type="text" class="form-control" id="addressL1" name="address1" [(ngModel)]="userItem.address1" placeholder="Enter Address Line 1" required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="addressL2" name="address2" [(ngModel)]="userItem.address2" placeholder="Enter Address Line 2" required>
</div>
<div class="form-group">
<input type="password" class="form-control" id="password" name="password" [(ngModel)]="userItem.password" placeholder="Enter Password" required>
</div>
<div class="form-group">
<input type="password" class="form-control" id="confPassword" name="confPassword" placeholder="Confirm Password" required>
</div>
<button type="submit" value="submit" class="btn btn-primary">Register</button>
</form>
</div>
Related
I'm working on an angular project and I want to develop a form, validate it, and save data in my database with php and mysql. I tried to do this but it doesn't work. I got these errors.
Property 'dataService' does not exist on type 'AppComponent'.
'data' is declared but its value is never read.
Parameter 'data' implicitly has an 'any' type.
Property 'router' does not exist on type 'AppComponent'.
'error' is declared but its value is never read.
Parameter 'error' implicitly has an 'any' type.
register.component.html
<h2 class="text-center">Registration</h2>
<div class="row">
<div class="col-md-3">
</div>
<div class="col-md-6 col-md-offset-3">
<div class="jumbotron">
<form [formGroup]="angForm" autocomplete="off" >
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" formControlName="name" autocomplete="off" class="form-control input-sm" required minlength="1" maxlength="250" placeholder="Name"
[class.is-invalid]="name.invalid && (name.dirty || name.touched)">
<div *ngIf="name.invalid && (name.dirty || name.touched)" class="invalid-feedback">
<div *ngIf="name.errors?.['required']">
This field is required.
</div>
</div></div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" name="email" formControlName="email" autocomplete="off" required minlength="1" maxlength="250" class="form-control input-sm" placeholder="Email"
[class.is-invalid]="email.invalid && (email.dirty || email.touched)">
<div *ngIf="email.invalid && (email.dirty || email.touched)" class="invalid-feedback">
<div *ngIf="email.errors?.['required']">
This field is required.
</div>
<div *ngIf="!email.errors?.['required'] && email.errors?.['emailValidator']">
Invalid email format.
</div>
</div></div>
<div class="form-group">
<label for="Password">Password</label>
<input type="password" name="Password" formControlName="password" required minlength="15" autocomplete="off" class="form-control input-sm" placeholder="Password"
[class.is-invalid]="password.invalid && (password.dirty || password.touched)">
<button type="button" class="btn btn-outline-secondary" (click)="user.showPassword = !user.showPassword">
<i class="bi" [ngClass]="{'bi-eye-fill': !user.showPassword, 'bi-eye-slash-fill': user.showPassword}"></i>
</button>
<div *ngIf="password.invalid && (password.dirty || password.touched)" class="invalid-feedback">
<div *ngIf="password.errors?.['required']">
This field is required.
</div>
<div *ngIf="password.errors?.['minlength']">
This field must have at least 8 characters.
</div>
</div></div>
<button type="submit" class="btn btn-success" (click)="validate(angForm1)">Register</button>
</form>
</div>
</div>
<div class="col-md-3">
</div>
</div>
register.component.ts
import { Component, OnInit } from '#angular/core';
import { FormGroup, FormControl, FormBuilder, Validators, NgForm, AbstractControl} from
'#angular/forms';
import { first } from 'rxjs/operators';
import { Router } from '#angular/router';
import { ApiService } from '../api.service';
import { emailValidator } from './email-validator.directive';
interface IUser {
name: string;
email: string;
password: string;
}
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {
angForm!: FormGroup;
user: IUser;
constructor() {
this.user = {} as IUser;
}
ngOnInit(): void {
this.angForm = new FormGroup({
name: new FormControl(this.user.name, [
Validators.required
]),
email: new FormControl(this.user.email, [
Validators.required,
EmailValidator,
]),
password: new FormControl(this.user.password, [
Validators.required,
Validators.minLength(8),
]),
});
}
get name() {
return this.angForm.get('name')!;
}
get email() {
return this.angForm.get('email')!;
}
get password() {
return this.angForm.get('password')!;
}
public validate(angForm1:any): void {
if (this.angForm.invalid) {
for (const control of Object.keys(this.angForm.controls)) {
this.angForm.controls[control].markAsTouched();
}
return;
}
else{ this.dataService. userregistration(angForm1.value.name,angForm1.value.email,
angForm1.value.password).pipe(first()).subscribe(
data => {
this.router.navigate(['login']);
},
error => {
});
}
this.user = this.angForm.value;
console.info('Name:', this.user.name);
console.info('Email:', this.user.email);
console.info('Password:', this.user.password);
}
}
register.php
<?php
include_once "database.php";
$postdata = file_get_contents("php://input");
if (isset($postdata) && !empty($postdata)) {
$request = json_decode($postdata);
$name = trim($request->name);
$pwd = mysqli_real_escape_string($mysqli, trim($request->pwd));
$email = mysqli_real_escape_string($mysqli, trim($request->email));
$sql = "INSERT INTO users(name,password,email) VALUES ('$name','$pwd','$email')";
if ($mysqli->query($sql) === true) {
$authdata = [
"name" => $name,
"pwd" => "",
"email" => $email,
"Id" => mysqli_insert_id($mysqli),
];
echo json_encode($authdata);
}
}
?>
api.service.ts
import {
Injectable,
Output,
EventEmitter
}
from '#angular/core';
import {
map
}
from 'rxjs/operators';
import {
HttpClient
}
from '#angular/common/http';
import {
Users
}
from './users';
#Injectable({
providedIn: 'root'
})
export class ApiService {
redirectUrl: string;
baseUrl: string = "http://localhost/angular_admin/php";
#Output() getLoggedInName: EventEmitter < any > = new EventEmitter();
constructor(private httpClient: HttpClient) {}
public userlogin(username: any, password: any) {
alert(username)
return this.httpClient.post < any > (this.baseUrl + '/login.php', {
username,
password
})
.pipe(map(Users => {
this.setToken(Users[0].name);
this.getLoggedInName.emit(true);
return Users;
}));
}
public userregistration(name: any, email: any, pwd: any) {
return this.httpClient.post < any > (this.baseUrl + '/register.php', {
name,
email,
pwd
})
.pipe(map(Users => {
return Users;
}));
}
//token
setToken(token: string) {
localStorage.setItem('token', token);
}
getToken() {
return localStorage.getItem('token');
}
deleteToken() {
localStorage.removeItem('token');
}
isLoggedIn() {
const usertoken = this.getToken();
if (usertoken != null) {
return true
}
return false;
}
}
In your constructor in your ts:
constructor(private router: Router,private apiservice: ApiService) {
this.user = {} as IUser;
}
public validate(angForm1:any): void {
if (this.angForm.invalid) {
for (const control of Object.keys(this.angForm.controls)) {
this.angForm.controls[control].markAsTouched();
}
return;
}
else{ this.apiservice. userregistration(angForm1.value.name,angForm1.value.email,
angForm1.value.password).pipe(first()).subscribe(
(data: any) => {
this.router.navigate(['login']);
},
error => {
});
}
this.user = this.angForm.value;
console.info('Name:', this.user.name);
console.info('Email:', this.user.email);
console.info('Password:', this.user.password);
}
In your html:
<h2 class="text-center">Registration</h2>
<div class="row">
<div class="col-md-3">
</div>
<div class="col-md-6 col-md-offset-3">
<div class="jumbotron">
<form [formGroup]="angForm" autocomplete="off" >
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" formControlName="name" autocomplete="off" class="form-control input-sm" required minlength="1" maxlength="250" placeholder="Name"
[class.is-invalid]="angForm.controls['name'].invalid && (angForm.controls['name'].dirty || angForm.controls['name'].touched)">
<div *ngIf="angForm.controls['name'].invalid && (angForm.controls['name'].dirty || angForm.controls['name'].touched)" class="invalid-feedback">
<div *ngIf="angForm.controls['name'].errors?.required">
This field is required.
</div>
</div></div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" name="email" formControlName="email" autocomplete="off" required minlength="1" maxlength="250" class="form-control input-sm" placeholder="Email"
[class.is-invalid]="angForm.controls['email'].invalid && (angForm.controls['email'].dirty || angForm.controls['email'].touched)">
<div *ngIf="angForm.controls['email'].invalid && (angForm.controls['email'].dirty || angForm.controls['email'].touched)" class="invalid-feedback">
<div *ngIf="angForm.controls['email'].errors.required">
This field is required.
</div>
<div *ngIf="!email.errors?.['required'] && email.errors?.['emailValidator']">
Invalid email format.
</div>
</div></div>
<div class="form-group">
<label for="Password">Password</label>
<input type="password" name="Password" formControlName="password" required minlength="15" autocomplete="off" class="form-control input-sm" placeholder="Password"
[class.is-invalid]="angForm.controls['password'].invalid && (angForm.controls['password'].dirty || angForm.controls['password'].touched)">
<button type="button" class="btn btn-outline-secondary" (click)="user.showPassword = !user.showPassword">
<i class="bi" [ngClass]="{'bi-eye-fill': !user.showPassword, 'bi-eye-slash-fill': user.showPassword}"></i>
</button>
<div *ngIf="angForm.controls['password'].invalid && (angForm.controls['password'].dirty || angForm.controls['password'].touched)" class="invalid-feedback">
<div *ngIf="angForm.controls['password'].errors.required">
This field is required.
</div>
<div *ngIf="angForm.controls['password'].errors.minlength">
This field must have at least 8 characters.
</div>
</div></div>
<button type="submit" class="btn btn-success" (click)="validate(angForm1)">Register</button>
</form>
</div>
</div>
<div class="col-md-3">
</div>
</div>
My Html file is as follows:
<h2>Welcome User!!!</h2>
<form class="container" action="/product">
<div>
<label for="mail"><b>Email-ID: [(ngModel)]</b></label>
<input type="text" placeholder="Enter mail ID" [(ngModel)]="mail" name="mail" required>
<label for="psw"><b>Phone Number</b></label>
<input type="text" placeholder="Enter Phone Number" [(ngModel)]="mail" name="phoneNumber" required>
<button (click)="myFunc()">NEXT</button>
</div>
</form>
My Typescript file is as follows:
import { Component, NgModule, OnInit } from '#angular/core';
import { Router, RouterModule, Routes } from '#angular/router';
import { MyProductPageComponent } from '../my-product-page/my-product-page.component';
#Component({
selector: 'app-my-home-page',
templateUrl: './my-home-page.component.html',
styleUrls: ['./my-home-page.component.css']
})
export class MyHomePageComponent implements OnInit {
phoneNumber = "";
mailID = "";
constructor(private router: Router) {
}
ngOnInit(): void {
}
myFunc() {
localStorage.setItem("phoneNumber", this.phoneNumber);
localStorage.setItem("mail", this.mailID);
this.router.navigate(['/products']);
}
}
const routes: Routes = [
{ path: 'MyProductPageComponent', component: MyProductPageComponent },
]
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
I want to fetch Phone number and Mail ID entered in form and save that in Local Storage. And redirect to the next page. Please help.
Am getting this error: Declaration expected.
you need to use ngmodel to bind the value with input control and same you can access in your component.
<h2>Welcome User!!!</h2>
<form class="container" action="/product">
<div>
<label for="mail"><b>Email-ID: </b></label>
<input type="text" [(ngModel)]="mailID" placeholder="Enter mail ID" name="mail" required>
<label for="psw"><b>Phone Number</b></label>
<input type="text" placeholder="Enter Phone Number" name="phoneNumber" [(ngModel)]="phoneNumber" required>
<button (click)="myFunc()">NEXT</button>
</div>
</form>
Add variables to phone/mail in your .ts components
Use this to variables in myFunc() to get the value of the variables
Use ngModel to bind the variables with the input of the user (set ngModel on the input not label).
Use import { NgModule } from '#angular/core'; in the app.module and NOT in your component
see working code
<h2>Welcome User!!!</h2>
<form class="container" action="/product">
<div>
<label for="mail"><b>Email-ID:</b></label>
<input type="text" placeholder="Enter mail ID" [(ngModel)]="mail" name="mail" required>
<label for="psw"><b>Phone Number</b></label>
<input type="text" placeholder="Enter Phone Number" [(ngModel)]="phoneNumber" name="phoneNumber" required>
<button (click)="myFunc()">NEXT</button>
</div>
</form>
phoneNumber = "";
mailID = "";
myFunc() {
localStorage.setItem("phoneNumber", this.phoneNumber);
localStorage.setItem("mail", this.mailID);
}
const routes: Routes = [
{ path: 'MyProductPageComponent', component: MyProductPageComponent },
]
The path variable should not have a component and you are using router.navigate('/products')
const routes: Routes = [
{ path: 'products', component: MyProductPageComponent },
]
These variables which are used in the ts should bind with the ngModel used in the template
phoneNumber = "";
mailID = "";
<h2>Welcome User!!!</h2>
<form class="container" action="/product">
<div>
<label for="mail"><b>Email-ID: </b></label>
<input type="text" placeholder="Enter mail ID" [(ngModel)]="mailID" name="mail" required>
<label for="psw"><b>Phone Number</b></label>
<input type="text" placeholder="Enter Phone Number" [(ngModel)]="phoneNumber" name="phoneNumber" required>
<button (click)="myFunc()">NEXT</button>
</div>
</form>
While i'm trying to send those values into the Firebase i'm getting this error: "Invalid document reference. Document references must have an even number of segments, but printers has 1"
ill post pictures of the code below maybe someone can shed some light on this thanks a lot!
Typescript:
import { Component, OnInit } from '#angular/core';
import { PrintersService } from '../printers.service';
#Component({
selector: 'app-addprinter',
templateUrl: './addprinter.component.html',
styleUrls: ['./addprinter.component.css']
})
export class AddprinterComponent implements OnInit {
constructor(private printersService: PrintersService) { }
ngOnInit() {
}
AddPrinter(form) {
this.printersService.AddPrinter(
form.value.hostName,
form.value.ip,
form.value.location,
form.value.manufacturer,
form.value.model,
form.value.specificLocation).then(
data => console.log(data))
.catch(err => console.log(err));
console.log(form);
}
}
Service:
import { Injectable } from '#angular/core';
import { AngularFirestore } from '#angular/fire/firestore';
#Injectable({
providedIn: 'root'
})
export class PrintersService {
constructor(private fs: AngularFirestore) { }
getAllPrinters() {
return this.fs.collection('Printers').valueChanges();
}
AddPrinter(HostName, Ip, Location, Manufacturer, Model, SpecificLocation) {
return this.fs.doc('Printers/').set({
HostName,
Ip,
Location,
Manufacturer,
Model,
SpecificLocation
});
}
}
HTML:
<br><br><br><br>
<h2 class="text-center">Add Printer</h2>
<form #f="ngForm" (ngSubmit)="AddPrinter(f)">
<input ngModel name="hostName" #hostname="ngModel" type="text" class="formControl" required placeholder="Enter HostName here">
<div class="alert alert-danger" *ngIf="hostname.touched &&hostname.errors?.required">The HostName is requied</div>
<input ngModel name="ip" #ip="ngModel" type="text" class="formControl" required placeholder="Enter Ip here">
<div class="alert alert-danger" *ngIf="ip.touched &&ip.errors?.required">The Ip is requied</div>
<input ngModel name="location" #location="ngModel" type="text" class="formControl" required placeholder="Enter Loctaion here">
<div class="alert alert-danger" *ngIf="location.touched &&location.errors?.required">The Location is requied</div>
<input ngModel name="manufacturer" #manufacturer="ngModel" type="text" class="formControl" required placeholder="Enter Manufacturer here">
<div class="alert alert-danger" *ngIf="manufacturer.touched &&manufacturer.errors?.required">The Manufacturer is requied</div>
<input ngModel name="Model" #model="ngModel" type="text" class="formControl" required required placeholder="Enter Model here">
<div class="alert alert-danger" *ngIf="model.touched &&model.errors?.required">The Model is requied</div>
<input ngModel name="specificLocation" #specificLocation="ngModel" type="text" class="formControl" required placeholder="Enter Specific Location here">
<div class="alert alert-danger" *ngIf="specificLocation.touched && specificLocation.errors?.required">The Specific Location is requied</div>
<button class="btn btn-primary" [disabled]="f.invalid">Send</button>
</form>
The error is complaining about this line:
this.fs.doc('Printers/').set({ ... })
If you want to create a document with set(), you must provide the full path including the collection where it lives, for example "Printers/printer_id".
If you are trying to add a new document with a random ID, use add() instead of set().
this.fs.collection('Printers').add({ ... })
I've been battling with these block of codes for some days, and even when i try initializing it as an object i get errors.
this is my restaurantForm.ts file
import { Component, OnInit } from '#angular/core';
import {RestaurantService} from '../../restaurant.service';
import {ProductService} from '../../product.service';
import {ActivatedRoute, Router} from '#angular/router';
import 'rxjs/add/operator/take';
import {Product} from '../../model/product';
#Component({
selector: 'app-product-form',
templateUrl: './restaurant-form.component.html',
styleUrls: ['./restaurant-form.component.css']
})
export class RestaurantFormComponent implements OnInit {
restaurants$;
id;
product: Product;
constructor(private restaurantService: RestaurantService,
private productService: ProductService,
private route: ActivatedRoute,
private router: Router) {
this.restaurants$ = this.restaurantService.getAll();
this.id = this.route.snapshot.paramMap.get('id');
if (this.id) {
this.productService.get(this.id).take(1).subscribe(p => this.product = p);
}
this.product = new Product();
}
save(product) {
if (this.id) {
this.productService.update(this.id, product);
} else {
this.productService.create(product);
}
this.router.navigate(['/admin/restaurants']);
}
delete() {
if (!confirm('Are you sure you want to delete this product?')) { return ; }
this.productService.delete(this.id);
this.router.navigate(['/admin/restaurants']);
}
ngOnInit() {
}
}
this is my product model
export interface Product {
$key: string;
title: string;
price: number;
restaurant: string;
imageUrl: string;
}
My restaurantForm.html
<div class="container">
<div class="row">
<div class="col-md-6">
<form #f="ngForm" (ngSubmit)="save(f)">
<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-danger alert" *ngIf="title.touched && title.invalid">
Title is required.
</div>
</div>
<div class="form-group">
<label for="price">Delivery Price</label>
<div class="input-group">
<span class="input-group-addon">₦</span>
<input #price="ngModel" [(ngModel)]="product.price" name="price" id="price"
type="number" class="form-control" required [min]="0">
</div>
<div class="alert alert-danger" *ngIf="price.touched && price.invalid">
<div *ngIf="price.errors.required">
Delivery Price is required
</div>
<div *ngIf="price.errors.min">
Delivery Price should be 0 or higher.
</div>
</div>
</div>
<div class="form-group">
<label for="restaurant">Restaurant</label>
<select #restaurant="ngModel" [(ngModel)]="product.restaurant" name="restaurant" id="restaurant" class="form-control" required>
<option value=""></option>
<option *ngFor="let r of restaurants$ | async" [value]="r.$key">
{{ r.name }}
</option>
</select>
<div class="alert alert-danger" *ngIf="restaurant.touched && restaurant.invalid">
Please select a restaurant.
</div>
</div>
<div class="form-group">
<label for="imageUrl">Image Url</label>
<input #imageUrl="ngModel" [(ngModel)]="product.imageUrl" name="imageUrl"
id="imageUrl" type="text" class="form-control" required url>
<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">Please enter a valid Url.</div>
</div>
</div>
<button class="btn btn-primary">Save</button>
<button type="button" (click)="delete()" class="btn btn-danger">Delete</button>
</form>
</div>
<div class="col-md-6">
<app-product-card [product]="product" [showActions]="false"></app-product-card>
</div>
</div>
</div>
I get the same errors with price, $key, restaurant and imageUrl.
thanks in advance. Although Ive looked up some solutions saying i should use elvis Operator e.g 'product?.title' this method isnt still working.
Because product is undefined, you need to declare and initialize it with empty object inside the constructor or ngOninit.
EDIT:
You need to have the Product declared in the component as,
const product : Produce = { $key: "", title: "",price:0,restuarant :"" ,imageurl:"" };
When the template get initialized, the product is undefined and it continues until the response return from API. Add a check for the template where you bind the object properties.Do the same for price etc.
<input *ngIf="product.title" #title="ngModel" [(ngModel)]="product.title" name="title" id="title" type="text" class="form-control" required>
I am getting the following error on browser console after clicking on Submit button.
In this application I am trying to get information about the Student uploaded code below.
I am unable to find why this error is shown on console.
I have correctly added the formControlName.
Component
import { Component, OnInit, Inject } from '#angular/core';
import { FormGroup, FormControl, Validators, FormBuilder, AbstractControl } from '#angular/forms';
#Component({
selector: 'app-new-record',
templateUrl: './new-record.component.html',
styleUrls: ['./new-record.component.css']
})
export class NewRecordComponent implements OnInit {
myFormGroup: FormGroup;
constructor(private formBuilder: FormBuilder) {
this.myFormGroup = this.formBuilder.group({
name: new FormControl('', Validators.compose([
Validators.required
])),
claz: new FormControl('BCA'),
admissionYear: new FormControl(Validators.compose([Validators.required]))
});
}
ngOnInit() {
}
onSubmit(student) {
console.log('onSubmit called !');
}
}
Template
<form [formGroup]="myFormGroup"
(ngSubmit)="onSubmit(form.value)">
<div class="form-group">
<label for="claz">Class:</label> <select name="claz" formControlName="claz">
<option value="MCA">MCA</option>
<option value="BCA">BCA</option>
<option value="M.Sc">M.Sc</option>
<option value="B.Tech">B.Tech</option>
</select>
</div>
<div class="form-group">
<label for="name">Name:</label> <input type="text"
class="form-control" id="name" formControlName="name">
</div>
<div class="form-group">
<label for="admissionYear">Admission Year:</label> <input type="number"
class="form-control" id="admissionYear" formControlName="admissionYear">
</div>
<button type="submit" class="btn btn-default" >Submit</button>
</form>
There is no form defined, instead use myFormGroup which has been defined as formGroup
(ngSubmit)="onSubmit(myFormGroup.value)"