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>
Related
I have a problem trying to dynamically grab the text and send it to my e-mail. It works when manually typing into TS onSendEmail. I am using free email hosting server and the assets folder has required files needed
HTML code
<form (ngSubmit)="onSendEmail(addEmailForm)" #addEmailForm ="ngForm">
<fieldset>
<legend>Contact us</legend>
<label>Your name</label> <br>
<input ngModel name="name" type="text" placeholder="Your name" size="20" required ><br>
<label>E-mail address</label> <br>
<input ngModel name="email" type="text" placeholder="example#example.com" size="20" required><br>
<label>Subject</label> <br>
<input ngModel name="subject" type="text" size="20"><br>
<label>Body</label> <br>
<textarea ngModel name="body" type="text" cols="40" rows="6" required></textarea><br>
<button [disabled]="addEmailForm.invalid" >Send</button>
</fieldset>
</form>
Typescript code
import { HttpClient } from '#angular/common/http';
import { Component, OnInit, AfterViewInit } from '#angular/core';
import { NgForm } from '#angular/forms';
declare let Email: any;
import 'src/assets/smtp.js'; // available in assets folder
#Component({
selector: 'app-map',
templateUrl: './shops.component.html',
styleUrls: ['./shops.component.css']
})
export class ShopsComponent implements OnInit, AfterViewInit {
constructor(private http: HttpClient) { }
ngOnInit(): void { }
body: any
subject: any;
email: any;
name: any;
onSendEmail(addEmailForm: NgForm) {
Email.send({
Host : "smtp.elasticemail.com",
Username : "myemail#hotmail.com",
Password : "mypassword",
To : 'mysecondemail#hotmail.com',
Name: this.name,
From : this.email, // when I write these manually the email gets sent
Subject : this.subject,
Body : this.body,
}).then(
(message: any) => alert("E-mail sent, thank you.")
);
}
}
To get filled data from your from You should use:
onSendEmail(addEmailForm: NgForm) {
let data = addEmailForm.value;
//...
}
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>
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 have written a registration page component in Angular. I have followed what few tutorials there are and I have stumbled upon a very frustrating bug. Pressing the submit button on the form will simply cause the console to print out "undefined" when trying to access the NgForm's value. Accessing the "valid" field of the NgForm will return true or false, as expected.
the page:
<app-players></app-players>
<div class="container" style="text-align:center">
<h3>Register a new account!</h3>
<form #f="ngForm" (ngSubmit)="onSubmit(f)">
<label>Username:</label> <input type="text" id="username"
required #username="ngModel"
name="username" ngModel><br>
<label>Password:</label> <input type="password" id="password"
required #password="ngModel"
name="password" ngModel><br>
<label>Email:</label> <input type="text" id="email"
required #email="ngModel"
name="email" ngModel><br>
<button type="submit" class="btn btn-success" [disabled]="!newPlayerEntry.form.valid">Submit</button>
</form>
</div>
<div id = "result">
</div>
The component:
import { Component, OnInit } from '#angular/core';
import { NgForm } from '#angular/forms';
import { NewPlayer } from './new-player';
#Component({
selector: 'app-players-register',
templateUrl: './players-register.component.html',
styleUrls: ['./players-register.component.css']
})
export class PlayersRegisterComponent implements OnInit {
constructor() {
}
ngOnInit() {
}
onSubmit(f: NgForm) {
console.log(f.value);
}
}
You need remove [disabled]="!newPlayerEntry.form.valid" and change to [disabled]="!f.valid"
This is working version
https://stackblitz.com/edit/angular-mgmmsq?file=src%2Fapp%2Fapp.component.html
I'm starting with Angular and I'm on a project where I have to validate the inputs so they can't be left clear, every input must me completed.
It's an html and we have a .ts file.
This is an extract of the html:
<div class="form-group">
<input type="text"
class="form-control"
id="factory"
[(ngModel)]="factory.company">
</div>
I need to validate this factory input but when I was watching tutorials all I needed to do was to write 'required' inside the <input> and that was it but I had a <form> and every input was inside this form, and this html doesn't have a <form> and when I put one the design was horrible and I couldn't work.
Here is an example using required fields (in login page) :
<form [formGroup]='loginForm' (submit)="login(loginForm.value)">
<div class="col-md-6">
<div class="login-mail">
<input type="text" placeholder="Email" formControlName="email" required="">
<i class="fa fa-envelope"></i>
</div>
<div class="login-mail">
<input type="password" placeholder="Password" formControlName="password" pattern=".{8,20}" required="">
<i class="fa fa-lock"></i>
</div>
</div>
<div class="col-md-6 login-do">
<label class="hvr-shutter-in-horizontal login-sub">
<input type="submit" value="login" >
</label>
</div>
<div class="clearfix"> </div>
</form>
in the login.component.ts , u should make some changes:
1) import some modules :
import { FormBuilder, FormGroup, Validators} from '#angular/forms';
2) in oninit function :
loginForm: FormGroup;
constructor(private fb : FormBuilder) {}
ngOnInit(){
this.loginForm = this.fb.group({
email : ["", Validators.required],
password : ["", Validators.required]
});
}
Hope that helps u :)
I would think that you should be able to add a form element. However, if you cannot as you have said then you can add the ngForm directive onto any element to achieve the same behavior as having the form element.
See this plunker for examples using ReactiveFormsModule and FormsModule:
Plunker
//our root app component
import {Component, OnInit, NgModule} from '#angular/core'
import {ReactiveFormsModule, FormsModule, FormControl, Validators} from '#angular/forms'
import {BrowserModule} from '#angular/platform-browser'
#Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
<div class="form-group">
<label>Model Driven Form</label>
<input type="text"
class="form-control"
id="companyModel"
[formControl]="companyModel">
<span [hidden]="companyModel.valid || companyModel.pristine">REQUIRED!</span>
</div>
<div class="form-group" ngForm #myForm="ngForm">
<label>Template Driven Form</label>
<input type="text"
class="form-control"
name="companyTemplate"
ngModel
id="companyTemplate"
#companyTemplate="ngModel"
required>
<span [hidden]="companyTemplate.valid || companyTemplate.pristine">REQUIRED!</span>
</div>
</div>
`,
})
export class App implements OnInit {
name:string;
companyModel: FormControl
constructor() {
this.name = 'Form Validation Demo'
}
ngOnInit() {
this.companyModel = new FormControl('', Validators.required)
}
}
#NgModule({
imports: [ BrowserModule, ReactiveFormsModule, FormsModule ],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}