There is a form on angular 8
my-form.component.html
<div class="container">
<form novalidate [formGroup]="registrationForm">
<div class="form-group">
<label for="firstName">Имя:</label>
<input #spy required pattern=[A-Za-zА-Яа-яЁё]{2,} name="firstName" id="firstName" type="text" class="form-control" formControlName="firstName">
</div>
<div class="form-group">
<label for="lastName">Фамилия:</label>
<input #spy required pattern=[A-Za-zА-Яа-яЁё]{2,} name="lastName" id="lastName" type="text" class="form-control" formControlName="lastName">
</div>
<div class="form-group">
<label for="email">E-mail:</label>
<input #spy required email name="email" id="email" type="email" class="form-control" formControlName="email">
</div>
<!--{{ spy.className }}-->
<button type="submit" class="btn btn-succes" (click)="submit(myForm)">Отправить</button>
</form>
When the user writes data, the submit button should send data to the API using the POST method.
If you need any code, leave a comment
ts code:
import { FormGroup, FormControl } from '#angular/forms';
import {HttpClient} from '#angular/common/http';
#Component({
selector: 'app-my-form',
templateUrl: './my-form.component.html',
styleUrls: ['./my-form.component.css']
})
export class MyFormComponent implements OnInit {
registrationForm: FormGroup;
constructor() { }
ngOnInit() {
this.registrationForm = new FormGroup({
firstName: new FormControl(),
lastName: new FormControl(),
email: new FormControl()
});
}
}```
i have simple example for you....
reference
----html----
<header class="masthead">
<div class="container h-100">
<div class="row h-100 align-items-center justify-content-center">
<div class="col-6">
<div class="text-center">
<hello name="{{ name }}"></hello>
<hr>
</div>
<form #send="ngForm" (ngSubmit)="sendFRMData(send.value)">
<div class="form-group">
<label for="title" class="text-muted">Title</label>
<input type="text" class="form-control" id="title"
name="titlefrm" ngModel #title='ngModel' required>
<span class="help-block text-danger" *ngIf="!title.valid &&
title.touched">Please give Title!!</span>
</div>
<div class="form-group">
<label for="body" class="text-muted">Body</label>
<input type="text" class="form-control" id="body" name="bodyfrm" ngModel
#body='ngModel' required>
<span class="help-block text-danger" *ngIf="!body.valid &&
body.touched">Please
give Body!!</span>
</div>
<div class="form-group">
<label for="userId" class="text-muted">UserID</label>
<input type="text" class="form-control" id="userId" name="userIdfrm" ngModel
#userid='ngModel' required>
<span class="help-block text-danger" *ngIf="!userid.valid &&
userid.touched">Please give UserID!!</span>
</div>
<div class="row">
<div class="col-sm-6">
<input class="form-control btn btn-success" type="submit"
[disabled]='!send.valid'>
</div>
<div class="col-sm-6">
<input class="form-control btn btn-info" type="button" value="EDIT"
(click) = 'onEdit()'>
</div>
</div>
</form>
</div>
</div>
</div>
</header>
----ts----
import { NgForm } from '#angular/forms';
#ViewChild('send') send: NgForm;
constructor(private sendData: HttpService) {
}
sendFRMData(data: any) {
const payload = {
title: data.titlefrm,
body: data.bodyfrm,
userId: data.userIdfrm
}
this.sendData.try(payload).subscribe(
(data: any) => {
this.respondedData = JSON.stringify(data);
this.alert = true;
}
);
}
----service----
try(data){
return
this.http.post('https://jsonplaceholder.typicode.com/posts',data,{
headers: {
"Content-type": "application/json; charset=UTF-8"
}
});
}
hope you get your answer...
Seems like you are not able to get form values in your submit function.
change your click event from (click)="submit(myForm)" to (click)="submit(myForm.value)" then in your submit function you can call post method
submit(formValueObject) {
console.log(formValueObject);
this.httpService.post(url, formValueObject).subscribe((res:any)=> {
//your response
})
}
I hope it helps
Related
I'm trying to create a form, the user insert data and i should show the data in another page just using vue js
I wrote this form
<form
id="main-contact-form"
class="contact-form row"
name="contact-form"
method="post"
>
<div class="form-group col-md-6">
<input
v-model="this.$store.state.name"
type="text"
name="name"
class="form-control"
required="required"
placeholder="اسم المنتج"
/>
</div>
<div class="form-group col-md-6">
<input
v-model="this.$store.state.price"
type="text"
name="email"
class="form-control"
required="required"
placeholder="السعر"
/>
</div>
<div class="form-group col-md-6">
<select
name="subject"
class="form-control"
v-model="this.$store.state.sub"
>
<option value="1">اكسسوريز</option>
<option value="2">عنايه</option>
<option value="3">مكياج</option>
<option value="4">شنط</option>
<option value="5">عطور</option>
<option value="6">اجهزه</option>
<option value="7">ملابس نساء</option>
<option value="8">رجال</option>
</select>
</div>
<div class="form-group col-md-6">
<input
:value="img"
type="file"
name="image"
class="form-control"
placeholder="اختر صورة المنتج"
/>
</div>
<div class="form-group col-md-12">
<textarea
v-model="this.$store.state.message"
name="message"
id="message"
required="required"
class="form-control"
rows="8"
placeholder="وصف المنتج أو نبذة عنه"
></textarea>
</div>
<div class="form-group col-md-12">
<input
#submit.prevent="this.$store.state.add"
type="submit"
name="submit"
class="btn btn-primary pull-right"
value="اضافة"
/>
</div>
</form>
this is my data and function i import them from store
export default createStore({
state: {
name: "",
price: "",
sub: "",
img: "",
message: "",
date: "new Date(Date.now()).toLocaleString()",
pro: [],
add: function () {
var New = {
nName: this.name,
nPrice: this.price,
nSub: this.sub,
nImg: this.img,
nDate: this.date,
};
this.name = "";
this.price = "";
this.sub = "";
this.pro.push(New);
alert(5);
// this.$router.push("/control-panel");
},
},
mutations: {},
actions: {},
modules: {},
});
When I press the button, i have this error
( Cannot POST /add-new-product ),
what should i do or what's the wrong with my code
"add" function should not be at "state" object but moved into "actions"
since it calls (as I can guess) an api to save the object
"generally if you want to modify/mutate your state, you do that in functions declared in mutations:{} and if you make api calls which are asychronous operations you declare functions in actions:{}"
e.x.
export default createStore({
actions:{
add:function(context,params){
return new Promise(function(resolve){
//call your api with ajax, assume that it returns correct
//commit your object to "add" function of mutations
context.commit('add',params);
});
}
}
})
after "add" actions returns successfully from the "api" request then you should have another
"add" function in mutations which will mutate your "pro" attribute of state
and any other "state" attributes/properties
e.x.
mutations:{
add:function(state,obj){
state.name = "";
state.price = "";
state.sub = "";
state.pro.push(obj);
alert(5);
}
}
rewrite also your vue "Form" component by adding an "submit" method (which will call the "store action") as follows and move to the "form" tag
<template>
<form #submit.prevent="submit"
id="main-contact-form"
class="contact-form row"
name="contact-form"
method="post"
>
<div class="form-group col-md-6">
<input
v-model="this.$store.state.name"
type="text"
name="name"
class="form-control"
required="required"
placeholder="اسم المنتج"
/>
</div>
<div class="form-group col-md-6">
<input
v-model="this.$store.state.price"
type="text"
name="email"
class="form-control"
required="required"
placeholder="السعر"
/>
</div>
<div class="form-group col-md-6">
<select
name="subject"
class="form-control"
v-model="this.$store.state.sub"
>
<option value="1">اكسسوريز</option>
<option value="2">عنايه</option>
<option value="3">مكياج</option>
<option value="4">شنط</option>
<option value="5">عطور</option>
<option value="6">اجهزه</option>
<option value="7">ملابس نساء</option>
<option value="8">رجال</option>
</select>
</div>
<div class="form-group col-md-6">
<input
:value="img"
type="file"
name="image"
class="form-control"
placeholder="اختر صورة المنتج"
/>
</div>
<div class="form-group col-md-12">
<textarea
v-model="this.$store.state.message"
name="message"
id="message"
required="required"
class="form-control"
rows="8"
placeholder="وصف المنتج أو نبذة عنه"
></textarea>
</div>
<div class="form-group col-md-12">
<input
type="submit"
name="submit"
class="btn btn-primary pull-right"
value="اضافة"
/>
</div>
</form>
</template>
<script>
export default{
methods:{
submit:function(){
this.$store.dispatch("add", {
nName: this.$store.state.name,
nPrice: this.$store.state.price,
nSub: this.$store.state.sub,
nImg: this.$store.state.img,
nDate: this.$store.state.date,
});
}
}
}
</script>
you can find a working example here
https://codesandbox.io/s/vuex-store-forked-d8895
I have a Form (multiple Input fields) inside ngFor and i want to get values and validate them and add them to Users array to send it back to API.
<form [formGroup]="registerForm" (ngSubmit)="onSubmit()">
<div *ngFor="let user of users">
<div class="form-group">
<label>First Name</label>
<input type="text" formControlName="firstName" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.firstName.errors }" />
<div *ngIf="submitted && f.firstName.errors" class="invalid-feedback">
<div *ngIf="f.firstName.errors.required">First Name is required</div>
</div>
</div>
<div class="form-group">
<label>Last Name</label>
<input type="text" formControlName="lastName" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.lastName.errors }" />
<div *ngIf="submitted && f.lastName.errors" class="invalid-feedback">
<div *ngIf="f.lastName.errors.required">Last Name is required</div>
</div>
</div>
</div>
<div class="form-group">
<button [disabled]="loading" class="btn btn-primary">Register</button>
</div>
</form>
.ts
export class AppComponent {
users=[
{id: 1},
{id: 2},
{id: 3}
]
registerForm: FormGroup;
submitted = false;
constructor(private formBuilder: FormBuilder){
this.registerForm = this.formBuilder.group({
firstName: ['', Validators.required],
lastName: ['', Validators.required]
});
}
get f() { return this.registerForm.controls; };
onSubmit() {
this.submitted = true;
// stop here if form is invalid
if (this.registerForm.invalid) {
return;
}
console.log(this.registerForm.value) // here i am getting value from last edited index.
}
}
Edit:
Stackblitz Exmple
You have to create array of FormGroup using users array.
Try this:
component.ts
this.registerForm = this.formBuilder.group({
userDetails: this.formBuilder.array(this.users.map(item=>{
return this.createItem(item)
})),
});
Since userDetails control is array of formGroup you don't need to use users array in html.
component.html
<form [formGroup]="registerForm" (ngSubmit)="onSubmit()">
<div formArrayName="userDetails" *ngFor="let item of registerForm.get('userDetails').controls; let i = index;">
<div [formGroupName]="i">
<div class="form-group">
<label>First Name</label>
<input type="text" formControlName="firstName" class="form-control" />
<div *ngIf="submitted && registerForm.controls['userDetails'].invalid" class="invalid-feedback">
<div>First Name is required</div>
</div>
</div>
<div class="form-group">
<label>Last Name</label>
<input type="text" formControlName="lastName" class="form-control" />
<div *ngIf="submitted && registerForm.controls['userDetails'].invalid" class="invalid-feedback">
<div>Last Name is required</div>
</div>
</div>
</div>
</div>
<div class="form-group">
<button [disabled]="loading" class="btn btn-primary">Register</button>
</div>
</form>
Example
you cant use a simple FormControl, for array values. formControl is only for a single value, so only the last edited value will be attached to them, you need to use
https://angular.io/api/forms/FormArray for that
When i try to submit a record to my SQL from vue component with laravel API nothing happens. I have compared my code to other working code but nothing seem to work.
Here is my register method:
register() {
axios
.post('/api/register', this.user)
.then(res => {
console.log(user)
})
.catch(err => {
console.log(err.message)
})
},
Here is the register form:
<template>
<form>
<div class="form-group">
<input
type="text"
v-model="user.name"
name="username"
class="form-control"
id="name"
placeholder="Email or username"
/>
<div class="validation"></div>
</div>
<div class="form-group">
<input
v-model="user.email"
type="email"
class="form-control"
name="email"
id="password"
placeholder="Your Email"
/>
<div class="validation"></div>
</div>
<div class="form-group">
<input
v-model="user.password"
type="password"
class="form-control"
name="password"
placeholder="Your Password"
data-rule="password"
/>
<div class="validation"></div>
</div>
<div id="errormessage"></div>
<div class="text-center">
<button type="submit" title="Register" v-on:click="register">Login</button>
</div>
</form>
</template>
My laravel page:
<section id="pricing" class="wow fadeInUp section-bg">
<div class="container">
<header class="section-header">
<h3>Register</h3>
<p>Come prepared!!</p>
</header>
<div class="row flex-items-xs-middle flex-items-xs-center">
<div class="col-xs-12 col-lg-6">
<div class="card">
<div class="card-header">
<div id="app">
<register></register>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
Here is my controller:
if ($v->fails())
{
return response()->json([
'status' => 'error',
'errors' => $v->errors()
], 422);
}
$user = new User;
$user->name = $request->name;
$user->email = $request->email;
$user->password = Hash::make($request->password);
$user->save();
return response()->json(['status' => 'success'], 200);
}
The record should post successfully, however nothing happens. I only see the parameters on my url like so, and I don't get any error on console.
You'll need to prevent the default form submission behavior first, then trigger your own register method.
<form #submit.prevent="register">
I am trying to change inner HTML content of a div by id with another div in angular component method. I am able to call populateEndpointHomeContent() and get that content but not further content. Actually those methods populateAddEndpoint() and populateAddEndpointForm are not getting called on click. I am not getting any console error also. Any idea how I can get this?
endpoint.component.html
<div id="endpoint_home"></div>
<div id="endpoint_home_content" style="display:none">
<button class="btn btn-sm" (click)="populateAddEndpoint();">+ Add Endpoint</button>
</div>
<!-- Add Endpoint DIVS Starts -->
<div id="add_endpoint_home" style="display:none">
<form #endpointForm="ngForm">
<section class="form-block">
<div class="form-group">
<label for="endPointType">Select Endpoint Type</label>
<div class="select">
<select id="endPointType" (change)="populateAddEndpointForm(this.value);">
<option>MACHINE</option>
<option>K8S_CLUSTER</option>
<option>AWS</option>
<option>DOCKER</option>
<option>VCENTER</option>
<option>WAVEFRONT</option>
<option>VRNI</option>
</select>
</div>
</div>
<div id="add_endpoint_form"></div>
<button type="submit" class="btn btn-primary">ADD</button>
</section>
</form>
</div>
<div id="add_machine_form" style="display:none">
<div class="form-group">
<label for="name">Endpoint Name</label>
<input type="text" placeholder="Endpoint Name" size="42" id="name" name="name" [(ngModel)]="name" required>
</div>
<div class="form-group">
<label for="credentialsName">Credential Name</label>
<div class="select">
<select id="credentialsName">
<option>MACHINE</option>
</select>
</div>
</div>
<button type="button" class="btn btn-primary">ADD CREDENTIAL</button>
<div class="form-group">
<label for="host">Machine Host/IP</label>
<input type="text" placeholder="0.0.0.0" size="42" id="host" name="host" [(ngModel)]="host" required>
</div>
<div class="form-group">
<label for="sshPort">SSH Port</label>
<input type="number" placeholder="22" size="42" id="sshPort" name="sshPort" [(ngModel)]="sshPort" required>
</div>
<div class="form-group">
<label for="timeout">SSH Timeout</label>
<input type="number" placeholder="60" size="42" id="timeout" name="timeout" [(ngModel)]="timeout" required>
</div>
<div class="form-group">
<label for="osType">OS Type</label>
<div class="select">
<select id="osType">
<option>WINDOWS</option>
<option>LINUX</option>
</select>
</div>
</div>
</div>
<!-- Add Endpoint DIVS Ends -->
EndpointComponent
import { Component, OnInit } from '#angular/core';
import { EndpointService } from './endpoint.service';
#Component({
selector: 'app-endpoint',
templateUrl: './endpoint.component.html',
styleUrls: ['./endpoint.component.scss']
})
export class EndpointComponent implements OnInit {
constructor(private endpointService: EndpointService) { }
public wavefrontendpoints: any;
ngOnInit() {
this.populateEndpointHomeContent();
this.endpointService.getAllEndpoints().subscribe(res => this.wavefrontendpoints = res.response[0]);
}
public populateEndpointHomeContent() {
document.getElementById('endpoint_home').innerHTML = document.getElementById('endpoint_home_content').innerHTML;
}
public populateAddEndpoint() {
console.log('Inside populateAddEndpoint...');
document.getElementById('endpoint_home').innerHTML = document.getElementById('add_endpoint_home').innerHTML;
}
public populateAddEndpointForm(endPointType) {
console.log('Inside populateAddEndpointForm...');
if(endPointType === 'MACHINE') { document.getElementById('add_endpoint_form').innerHTML = document.getElementById('add_machine_form').innerHTML; }
}
}
Trying to render HTML content from its innerHTML will not have its prototype functions work.
Your HTML will be visible, but it won't make their click events trigger, because innerHTML only contains the HTML markup, not the function or event prototypes.
Go through Angular's Guide on Dynamic Component Loader, which is about loading dynamic content in an HTML page.
I am trying to do some email validation on an angular 2 form, however I cannot make it work.
Here is my register.html form :-
<div class="row">
<div class="col-lg-10 col-offset-2">
<div class="well bs-component">
<form name="registerForm" class="form-horizontal" (ngSubmit)="onSubmit(email, password, name, surname, username, homephonenumber, mobilenumber)" >
<fieldset>
<legend>Register</legend>
<div class="form-group">
<label for="username" class="col-lg-2 control-label">UserName</label>
<div class="col-lg-10">
<input type="text" class="form-control" name="username" [(ngModel)]="username" placeholder="Username" required minlength="4" maxlength="20">
</div>
</div>
<div class="form-group">
<label for="email" class="col-lg-2 control-label">Email</label>
<div class="col-lg-10">
<input type="text" class="form-control" name="email" [(ngModel)]="email" placeholder="Email" required minlength="4" >
<div *ngIf="email.dirty && !email.valid" class="alert alert-danger">
<p *ngIf="email.errors.required">mailAddressis required.</p>
<p *ngIf="email.errors.incorrectMailFormat">Email format is invalid.</p>
</div>
</div>
</div>
<div class="form-group">
<label for="password" class="col-lg-2 control-label">Password</label>
<div class="col-lg-10">
<input type="password" class="form-control" name="password" [(ngModel)]="password" placeholder="Password" required minlength="4">
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<button type="reset" class="btn btn-default">Cancel</button>
<button type="submit" class="btn btn-primary">Register</button>
</div>
</div>
</fieldset>
</form>
</div>
and in my register.component.ts I have the following:-
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import {UserService} from 'app/services/user.service';
import {FormGroup, FormControl, Validators} from "#angular/forms";
#Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {
registerForm: FormGroup;
constructor(private _userService:UserService, private _router:Router) { }
ngOnInit() {
this.registerForm = new FormGroup({
email: new FormControl('', this.validateEmail)
});
}
onSubmit(email, password, name, surname, username, homephonenumber, mobilenumber){
this._userService.register(email, password, name, surname, username, homephonenumber, mobilenumber)
.subscribe((result) => {
// if(result.access_token != null) {
// this._router.navigate(['']);
// }
});
}
validateEmail(c: FormControl) {
let EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+#[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
return EMAIL_REGEXP.test(c.value) ? null : {
validateEmail: {
valid: false
}
};
}
Do I need anything else to make the validation work?
Thanks for all your help and time.
HTML5 is having email type that validates by default.
<input type="email" class="form-control" name="email" [(ngModel)]="email" placeholder="Email" required minlength="4" >
Other way around is to use ng-pattern
<input ng-pattern = '/^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i' type="email" name="email" class="form-control" ng-model="email" required="" />
<p class="help-block error-block">Enter a valid email address.</p>
try like this:
Html:
<form id="frmForgetPwd" name="frmForgetPwd" #frm="ngForm">
<div class="form-group">
<label>Registered Email Address</label>
<input type="email" class="form-control" focus
id="emailID" name="emailID" autofocus
#email="ngModel"
ngModel
required>
</div>
<button type="submit (click)="forgotPassword(email.value)">
Submit
</button>
</form>
component:
forgotPassword(emailid: string) {
this.errors = [];
if (emailid == "") {
this.errors.push(new error("invalidemail",Messages.EMAIL_IN_VALID));
return false;
}
let EMAIL_REGEXP = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if (!EMAIL_REGEXP.test(emailid)) {
this.errors.push(new error("invalidemail",Messages.EMAIL_IN_VALID));
return false;
}
}