Angular form doesn't send data dynamically - javascript

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

Related

How can I add a date to an object in Angular?

am sending an put request based on these files.
Venue.ts file
export class Venue {
id: number;
venueName: string;
cityName: string;
emailContact: string;
fighter1: string;
fighter2: string;
dateOfFight: Date;
active: boolean;
}
My Angular Component files:
create-venue.component.html
<h3>Create Event</h3>
<div [hidden]="submitted" style="width: 400px;">
<form (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="name">Venue Name</label>
<input type="text" class="form-control" id="venueName" required [(ngModel)]="venue.venueName" name="venueName">
</div>
<div class="form-group">
<label for="name">City Name</label>
<input type="text" class="form-control" id="cityName" required [(ngModel)]="venue.cityName" name="cityName">
</div>
<div class="form-group">
<label for="name">Email Contact</label>
<input type="text" class="form-control" id="emailContact" required [(ngModel)]="venue.emailContact" name="emailContact">
</div>
<div class="form-group">
<label for="name">Fighter 1 Contact</label>
<input type="text" class="form-control" id="fighter1" required [(ngModel)]="venue.fighter1" name="fighter1">
</div>
<div class="form-group">
<label for="name">Fighter 2 Contact</label>
<input type="text" class="form-control" id="fighter2" required [(ngModel)]="venue.fighter2" name="fighter2">
</div>
<div class="form-group">
<label for="name">Choose a time for your Event:</label>
<input type="datetime-local" class="form-control" id="dateOfFight" min="2021-01-01T00:00" max="2023-06-14T00:00" required [(ngModel)]="venue.dateOfFight" name="dateOfFight">
</div>
<button type="submit" class="btn btn-success">Submit</button>
</form>
</div>
<div [hidden]="!submitted">
<h4>You submitted successfully!</h4>
<!-- <button class="btn btn-success" (click)="newVenue()">Add</button> -->
</div>
create-venue.component.ts
import { VenueService } from '../venue.service';
import { Venue} from '../venue';
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
#Component({
selector: 'app-create-venue',
templateUrl: './create-venue.component.html',
styleUrls: ['./create-venue.component.css']
})
export class CreateVenueComponent implements OnInit {
venue: Venue = new Venue();
submitted = false;
constructor(private venueService: VenueService,
private router: Router) {}
ngOnInit() {
}
newVenue(): void {
this.submitted = false;
this.venue = new Venue();
}
save() {
this.venueService.createVenue(this.venue)
.subscribe(data => console.log(data), error => console.log(error));
this.venue = new Venue();
this.gotoList();
}
onSubmit() {
this.submitted = true;
this.save();
}
gotoList() {
this.router.navigate(['/venues']);
}
}
My current sent data in chrome:
I am quite new to javascript and angular, maybe this was answered before but I have no idea how to get the input data into the Venue object...
Edit:
This is my header tab:
I
using a string instead of Date type for the dateOfFight property will let you post to the backend without issue.
You can then generate the date with new Date(datestring) on your server if needed. On the front end you can look into date pipes which will help you format the string accordingly.
You also seem to not be capturing any values in your date input. Notice venue.dateOfFight is not even there. Perhaps try logging out your data before posting
You can use a string instead of date type dateOfFight: string;, and before saving, trasform it into a date format with Moment js.
moment(Date.now()).format('YYYY-MM-DD').toString()

Local Storage/Session Storage

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>

Can receive but cant send data to firebase, Code problem?

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({ ... })

Angular 8 error. ‘show’ does not exist on type

I'am new to angular 8.
I'am currently doing a small assignment for college but with this all Covid 19 thing happening communication with the lecture is limited and because of this is slowing my down.
I googled the error for ages and cant seem to find whats wrong.
Thanks.
<button (click)="show = !show">{{show ? 'Hide' : 'Add a car'}}</button>
<div *ngIf="show">
<form>
<label>Make</label>
<input type="text" name="make" placeholder="Enter Make" #make>
<label>Model</label>
<input type="text" name="model" placeholder="Enter Model" #model>
<label>Year</label>
<input type="text" name="year" placeholder="Enter Year" #year>
<button type="submit" (click)="addTheCar(make.value,
model.value,year.value)">Add the Car</button>
</form>
</div>
<div class="container">
<app-car *ngFor="let carData of carsData" [carData]="carData"></app-car>
</div>
This is the carlist.component.html(where the error sends me)
import { Component, OnInit } from '#angular/core';
import { ICar, Car } from '../interfaces/car';
import { CarApiService } from '../services/car-api.service';
#Component({
selector: 'app-carlist',
templateUrl: './carlist.component.html',
styleUrls: ['./carlist.component.css'],
providers: [CarApiService]
})
export class CarlistComponent implements OnInit {
carsData: ICar[];
constructor(private _carAPIService:CarApiService) { }
ngOnInit(): void{
this._carAPIService.getCarData().subscribe(carsData =>
{this.carsData = carsData});
}
addTheCar(make:string, model:string, year:string):boolean{
let tempCar:ICar;
tempCar= new Car(make,model,year);
this._carAPIService.addCarData(tempCar);
return false;
}
}
You have to define show in CarlistComponent.ts
export class CarlistComponent implements OnInit {
show:boolean;
It is what it says: there is no show property on your component. Add show = false; under your carsData line and it should go away.
try this
import { Component, OnInit } from '#angular/core';
import { ICar, Car } from '../interfaces/car';
import { CarApiService } from '../services/car-api.service';
#Component({
selector: 'app-carlist',
templateUrl: './carlist.component.html',
styleUrls: ['./carlist.component.css'],
providers: [CarApiService]
})
export class CarlistComponent implements OnInit {
carsData: ICar[];
show:boolean;
constructor(private _carAPIService:CarApiService) { }
ngOnInit(): void{
this._carAPIService.getCarData().subscribe(carsData =>
{this.carsData = carsData});
}
addTheCar(make:string, model:string, year:string):boolean{
let tempCar:ICar;
tempCar= new Car(make,model,year);
this._carAPIService.addCarData(tempCar);
return false;
}
}
specify a boolean value for show
export class CarlistComponent implements OnInit {
public show = true;
Only when show = true this div will get executed
<div *ngIf="show">
<form>
<label>Make</label>
<input type="text" name="make" placeholder="Enter Make" #make>
<label>Model</label>
<input type="text" name="model" placeholder="Enter Model" #model>
<label>Year</label>
<input type="text" name="year" placeholder="Enter Year" #year>
<button type="submit" (click)="addTheCar(make.value,
model.value,year.value)">Add the Car</button>
</form>
</div>

Submitting Angular form returns unavailable or undefined

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

Categories