INPUT DATE VALUE ANGULAR - html

SERVICE.TS
addP(nome: string, cognome: string, anno_n: string): Observable<any> {
return this.http.post<Partecipanti>(this.partecipantiUrl, {
nome: nome,
cognome: cognome,
anno_n: anno_n
}, this.httpOptions).pipe(
tap((newPartecipante: Partecipanti) => this.log(`partecipante aggiunto w/ id=${newPartecipante.id}`)),
catchError(this.handleError<Partecipanti>('addP'))
);
}
COMPONENT.TS
add(nome: string, cognome: string, anno_n: string): void {
this.PartecipantiService.addP(nome, cognome, anno_n).subscribe(res => {
console.log(res);
this.loadUser();
})
}
<form class="row row-cols-lg-auto g-3 align-items-center float-center" (ngSubmit)="add(nome.value, cognome.value, anno_n.value)" (ngSubmit)="loadUser()" style="justify-content: center;">
<div class="col-12">
<label class="visually-hidden" for="inlineFormInputGroupUsername">Nome</label>
<div class="input-group">
<input type="text" class="form-control" id="inlineFormInputGroupUsername" required #nome placeholder="Nome">
</div>
</div>
<div class="col-12">
<label class="visually-hidden" for="inlineFormInputGroupUsername">Cognome</label>
<div class="input-group">
<input type="text" class="form-control" id="inlineFormInputGroupUsername" required #cognome placeholder="Cognome">
</div>
</div>
<div class="col-12">
<label class="visually-hidden" for="inlineFormInputGroupUsername">Data di nascita</label>
<div class="input-group">
<input type="text" class="form-control" id="inlineFormInputGroupUsername" required #anno_n useValueAsDate placeholder="Data di nascita (GG/MM/AAAA)">
</div>
</div>
<div class="col-12">
<button type="submit" class="btn btn-primary shadow-lg">Salva</button>
</div>
</form>
How can I take the date value in my function "add"?
In my function add I have 3 field (name, surname and date), when I call my function add on a button I use (ngSubmit)="add(name.value, surname.value, date...?). What I have to use? Value is for string, I can't find something for Date! This part is on component.html Can you explain me how it works? My input is type="date"

I would suggest you use ngForm. This is the easiest for handling this scenario.
See here the Documentation: https://angular.io/api/forms/NgForm
Here is a working example i did: https://stackblitz.com/edit/angular-ivy-pqgewm?devtoolsheight=33&file=src/app/app.component.html
In Essence you want your HTML look like this:
<form #form="ngForm" (ngSubmit)="userService.submitForm(form)">
<div>
<label for="firstName">First Name</label>
<input name="firstName" id="firstName" type="text" ngModel required />
</div>
<div>
<label for="lastName">Last Name</label>
<input name="lastName" id="lastName" ngModel type="text" required />
</div>
<div>
<label for="dateOfBirth">Date of Birth</label>
<input name="dateOfBirth" id="dateOfBirth" ngModel type="date" required />
</div>
<br />
<button type="submit">Submit</button>
</form>
And your Submit function to look like this:
submitForm(form: NgForm) {
if (form.valid) {
const user: User = {
name: form.value['firstName'],
surname: form.value['lastName'],
birth: new Date(form.value['dateOfBirth']),
};
}
}

Related

#Input form child component

I am trying to separate the code responsible for the form into another component, and make it reusable.
I guess i should use #Input somehow. Then referr it in html. And pass values from it to post method. But how can i do it?
Backend, form and method worked fine when code were in same .ts. Im using Angular11.2.2
Here is my code:
**camel-form.component.ts **
camelForm = this.formBuilder.group({
id: [],
name: [''],
age: [],
guardian: this.formBuilder.group({
id: [],
name: [''],
lastName: [''],
email: ['']
})
});
**camel-form.component.html **
<form [formGroup]="camelForm">
<!-- part for camel-->
<h2 class="ml-3">Camel form</h2>
<div class="form-row ml-3">
<div class="form-group col-md-2">
<label for="id">id </label>
<input class="form-control" id="id" type="number" formControlName="id">
</div>
<div class="form-group col-md-2">
<label for="name">name </label>
<input class="form-control" id="name" type="text" formControlName="name">
</div>
<div class="form-group col-md-2">
<label for="age">age </label>
<input class="form-control" id="age" type="number" formControlName="age">
</div>
</div>
<!-- part for guardian-->
<h2 class="ml-3">Guardian form</h2>
<div class="form-row ml-3" formGroupName="guardian">
<div class="form-group col-md-2">
<label for="id">id </label>
<input class="form-control" id="id" type="number" formControlName="id">
</div>
<div class="form-group col-md-2">
<label for="name">name </label>
<input class="form-control" id="name" type="text" formControlName="name">
</div>
<div class="form-group col-md-2">
<label for="lastName">lastName</label>
<input class="form-control" id="lastName" type="text" formControlName="lastName">
</div>
<div class="form-group col-md-2">
<label for="email">email</label>
<input class="form-control" id="email" type="email" formControlName="email">
</div>
</div>
</form>
**rest.component.ts **
camel: Camel;
postCamel(): void {
this.camel = this.----------.value;
this.apiService.postCamel(this.camel).subscribe();
}
**rest.component.html **
<app-camel-form></app-camel-form>
<button class="btn-danger ml-3" type="submit" (click)="postCamel()">Submit</button>
First, I would move the submit button into the CamelForm component.
Second, to make the form re-usable for editing you'll need to provide an input for the data so it can be bound to the FormGroup instance. Example, omitting the component definition:
#Input()
camel: ICamel;
form: FormGroup;
initForm(camel?: ICamel): void {
this.form = this.formBuilder.group({
id: [camel ? camel.id : null],
name: [camel ? camel.name : null],
age: [],
guardian: this.formBuilder.group({
id: [camel ? camel.gaurdian.id : null],
name: [camel ? camel.gaurdian.name : null],
lastName: [camel ? camel.gaurdian.lastName : null],
email: [camel ? camel.gaurdian.email : null]
});
}
}
Now you can leverage the form in either case by supplying the input, or not:
<app-camel-form [camel]="camel"></app-camel-instance>
Hope that helps you out.
are you sure you want to make a submit button out of the form? if that is false then you can subscribe to submit event and emit it from your component (submit)="postCamel($event)". Otherwise - you want button out of the form I would propose to do like that
<app-camel-form #camelForm [camel]="camelData"></app-camel-form>
<button (click)="postCamel(camelForm.value)"
and in the form
ngOnChanges(changes) { // this method is needed if you want to pass data to the form
if(changes.camel) {
this.camelForm.patchValue(this.camel)
}
}
get value() {// this will make the form value be accessible from outside of form component
return this.camelForm.value;
}

Pass data from HTML page to typescript file

I have a ngForm for singup page. I have tried passing the data to the .ts file but failed to print them on console.
Here's my code:
<div class="column" style="padding: 7.5%">
<form #instituteForm="ngForm" (ngSubmit)="instituteLogin(instituteForm)">
<div class="form-group">
<label> Full Name </label>
<input
type="text"
ng-maxlength="10"
hint="Full Name"
name="patient"
id="name"
class="form-control"
[(ngModel)]="institute.patient">
<label> Phone Number </label>
<input
type="number"
hint="phone"
name="phoneno"
id="phone"
maxlength="10"
minlength="10"
class="form-control"
[(ngModel)]="institute.phoneno">
<label> Aadhar Number </label>
<input
type="number"
hint="aadhar"
id="aadhar"
name="aadhar"
maxlength="16"
minlength="16"
class="form-control"
[(ngModel)]="institute.aadhar">
<br><br>
</div>
<button id="signup" class="btn btn-primary" type="submit">Signup</button>
</form>
</div>
institute = {
patient: '',
phoneno: '',
aadhar: ''
};
instituteLogin(instForm: NgForm) {
console.log("Entered new patient");
console.log(instForm.value);
}
You have not added the FormsModule in app.module.ts.
import { FormsModule } from '#angular/forms';
#NgModule({
imports: [
// Other imports
FormsModule
]
})
Working demo : https://stackblitz.com/edit/angular-ybbamr
In this case it should be like this:
instituteLogin(): void{
console.log("Entered new patient");
console.log(this.institute);
}
Well, I think you should use FormControlName instead of ngModel.
html:
<div class="column" style="padding: 7.5%" >
<form [formGroup]="institute" #instituteForm (ngSubmit)="instituteLogin()">
<div class="form-group">
<label> Full Name </label>
<input type="text" ng-maxlength="10" hint="Full Name" id="name" class="form-
control" formControlName="patient">
<label> Phone Number </label>
<input type="number" hint="phone" id="phone" maxlength="10" minlength="10"
class="form-control" formControlName="phoneno">
<label> Aadhar Number </label>
<input type="number" hint="aadhar" id="aadhar" maxlength="16" minlength="16"
class="form-control" formControlName="aadhar">
<br><br>
<button id="signup" class="btn btn-primary"
routerLink="../../home/dashboard">Signup</button>
</div> </form>
</div>
ts:
institute:FormGroup;
instituteLogin(){
console.log("Entered new patient");
console.log(this.institute.value);
}
constructor(private formBuilder:FormBuilder) { }
ngOnInit() {
this.institute =this.formBuilder.group( {
patient: new FormControl(),
phoneno:new FormControl(),
aadhar:new FormControl()
});
}

Text area placeholder is not showing up while having no space or newline between opening and closing tags

My text area place holder is not showing up. All previous answers I have seen here describe there should be no space or new line between opening and closing tags of text area and my code don't have both. Is data-validation-required-message is creating problem ? How can I solve this.
Here is my code:
<div class="col-md-6">
<div class="form-group">
<textarea class="form-control" placeholder="Your Message *" id="message" required data-validation-required-message="Please enter a message."></textarea>
<p class="help-block text-danger"></p>
</div>
I go and try
<textarea class="form-control" placeholder="Your Message *" id="message" required data-validation-required-message="Please enter a message."></textarea>
But it`s work for me !:S
It works, check the snippet:
Demo: https://reactiveraven.github.io/jqBootstrapValidation/
$(function() {
prettyPrint();
$("input,textarea,select").jqBootstrapValidation(
{
preventSubmit: true,
submitError: function($form, event, errors) {
// Here I do nothing, but you could do something like display
// the error messages to the user, log, etc.
},
submitSuccess: function($form, event) {
alert("OK");
event.preventDefault();
},
filter: function() {
return $(this).is(":visible");
}
}
);
$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});
<link rel="stylesheet" href="https://reactiveraven.github.io/jqBootstrapValidation/css/prettify_bootstrap.css">
<link rel="stylesheet" href="https://reactiveraven.github.io/jqBootstrapValidation/css/bootstrap.css">
<script src="https://reactiveraven.github.io/jqBootstrapValidation/js/jQuery-1.7.2-min.js"></script>
<script src="https://reactiveraven.github.io/jqBootstrapValidation/js/bootstrap.js"></script>
<script src="https://reactiveraven.github.io/jqBootstrapValidation/js/prettify.js"></script>
<script src="https://reactiveraven.github.io/jqBootstrapValidation/js/jqBootstrapValidation.js"></script>
<form class="form-horizontal" novalidate>
<div class="control-group">
<label class="control-label" for="email">Email address</label>
<div class="controls">
<input type="email" name="email" id="email" required>
<p class="help-block">Email address we can contact you on</p>
</div>
</div>
<div class="control-group">
<label class="control-label" for="emailAgain">Email again</label>
<div class="controls">
<input type="email" data-validation-matches-match="email" data-validation-matches-message="Must match email address entered above" id="emailAgain" name="emailAgain">
<p class="help-block">And again, to check for speeling miskates</p>
</div>
</div>
<div class="control-group">
<label class="control-label" for="terms-and-conditions">Legal</label>
<div class="controls">
<label class="checkbox">
<input type="checkbox" id="terms-and-conditions" name="terms-and-conditions" required data-validation-required-message="You must agree to the terms and conditions">
I agree to the terms and conditions
</label>
<p class="help-block"></p>
</div>
</div>
<div class="control-group">
<label class="control-label">Quality Control</label>
<div class="controls">
<label class="checkbox">
<input type="checkbox" name="qualityControl[]" value="fast" data-validation-minchecked-minchecked="2" data-validation-minchecked-message="Choose two" data-validation-maxchecked-maxchecked="2" data-validation-maxchecked-message="You can't have it all ways" >
Fast
</label>
<label class="checkbox">
<input type="checkbox" name="qualityControl[]" value="cheap">
Cheap
</label>
<label class="checkbox">
<input type="checkbox" name="qualityControl[]" value="good">
Good
</label>
<p class="help-block"></p>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary">Test Validation <i class="icon-ok icon-white"></i></button><br />
</div>
</form>
Note
Now if you want to display this message Please enter a message. then you have to validate this using jQuery. Because its data-validation-required-message is used to display custom validation message.

How to pass the array values in HTTP POST method

I have the code like this:
empty values getting passing array object.
when log the details it's showing fine.
complaint-reg.component.html:
<div class="col-md-6 panel panel-default">
<h2>Complaint registration</h2>
<form #complaintRegForm="ngForm" (ngSubmit)="createComplaint(complaintRegForm.value)">
<div class="form-group">
<label>District:</label>
<input type="text" class="form-control" name="District" ngModel>
</div>
<div class="form-group">
<label>Subject:</label>
<input type="text" class="form-control" name="Subject" ngModel>
</div>
<div class="form-group">
<label>Description:</label>
<input type="text" class="form-control" name="Description" ngModel>
</div>
<div class="form-group">
<label>Place of occurence:</label>
<input type="text" class="form-control" name="PlaceOfOccurence" ngModel>
</div>
<div class="form-group">
<label>Name:</label>
<input type="text" class="form-control" name="Name" ngModel>
</div>
<div class="form-group">
<label>Gender:</label>
<input type="radio" class="form-control" name="Male" ngModel>Male
<input type="radio" class="form-control" name="Female" ngModel>Female
</div>
<div class="form-group">
<label>Address:</label>
<input type="text" class="form-control" name="Address" ngModel>
</div>
<div class="form-group">
<label>Mobile no:</label>
<input type="number" class="form-control" name="MobileNo" ngModel>
</div>
<div class="form-group">
<label>Email:</label>
<input type="text" class="form-control" name="Email" ngModel>
</div>
<div class="form-group">
<label>Date of occurence:</label>
<input type="text" class="form-control" name="DateOfOccurence" ngModel>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
complaint-reg.component.ts:
import { Component, OnInit } from '#angular/core';
import { ComplaintRegistrationService } from './complaint-registration.service';
#Component({
selector: 'app-complaint-registartion',
templateUrl: './complaint-registartion.component.html',
styleUrls: ['./complaint-registartion.component.css'],
providers:[ComplaintRegistrationService]
})
export class ComplaintRegistartionComponent implements OnInit {
constructor(private complaintCreation : ComplaintRegistrationService) { }
ngOnInit() {
}
complaintObj = {};
createComplaint(Obj){
console.log(Obj);
this.complaintCreation.createCompliants(Obj).subscribe();
}
}
and
complaint-reg.service.ts:
import { Injectable } from '#angular/core';
import { Http,Response } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class ComplaintRegistrationService{
private _url:string ="http://192.168.0.106:8000/app/complaint/create"
constructor(private _http:Http){}
createCompliants(complaintObj){
return this._http.post(this._url,complaintObj).map((response:Response)=>console.log(response));
}
}
passing empty values. Attaching screen
First of all, I want to point out, that what you are sending and what you are console logging, is NOT the same. Actually what you are logging what the backend is sending you, not what it has received, so your post request is actually probably sending data, it is just in the "wrong format".
Looking at your console, it seems that the problem is that you are sending the properties with upper camel case, but the backend expects you using lower camel case.
You didn't bind input elements to the ngModel. Add binding to input controls like this
<input type="text" class="form-control" name="District" [(ngModel)]="complaintObj.district" >
when you submit the form complaintObj should not be empty.

HTML AngularJs CSS Form submit

I'm having a problem when I submit the form.
So.. I fill all data on the formulary then I click save... The data is correctly saved, but after the submit, the fields are cleaned and then the inputs receive the css because the form is already submitted. I would like to don't keep the formulary 'submitted' when it is correctly saved.
My code is going bellow.
HTML code
<form name="citizenForm" ng-submit="citizensCtrl.createCitizen(citizenForm)" class="css-form" novalidate>
<div class="form-group">
<label for="citizen_name">Nome *</label>
<input type="text" class="form-control" id="citizen_name" placeholder="Nome" ng-model="citizensCtrl.citizen.name" required>
<div class="form-group">
<label for="citizen_birthday">Nascimento *</label>
<uib-datepicker ng-model="citizensCtrl.citizen.birthday" class="well well-sm" datepicker-options="citizensCtrl.dateOptions" required></uib-datepicker>
</div>
<div class="form-group">
<label for="citizen_cell_phone">Celular *</label>
<input type="text" class="form-control" id="citizen_cell_phone" placeholder="Celular" ng-model="citizensCtrl.citizen.cell_phone" required>
</div>
<div class="form-group">
<label for="citizen_phone">Telefone *</label>
<input type="text" class="form-control" id="citizen_phone" placeholder="Telefone" ng-model="citizensCtrl.citizen.phone" required>
</div>
<hr>
<h4>Endereço</h4>
<div class="form-group">
<label for="citizen_address_district">Bairro *</label>
<select id="citizen_address_district" ng-model="citizensCtrl.citizen.address.district" class="form-control"
ng-options="district as district.name for district in citizensCtrl.districts" ng-change="citizensCtrl.getAddresses()" required>
<option value=""> Bairro</option>
</select>
</div>
<div class="form-group">
<label for="citizen_address_public_place">Rua *</label>
<input type="text" ng-model="citizensCtrl.citizen.address.public_place" id="citizen_address_public_place"
uib-typeahead="address as address.public_place for address in citizensCtrl.addresses | filter:{public_place: citizensCtrl.citizen.address.public_place} | limitTo:5"
typeahead-min-length="6" typeahead-select-on-exact="true"
typeahead-on-select="citizensCtrl.getZipCodes()"
typeahead-loading="loadingLocations"
ng-disabled="!citizensCtrl.citizen.address.district.id"
typeahead-no-results="noResults" class="form-control" required>
<i ng-show="loadingLocations" class="glyphicon glyphicon-refresh"></i>
<div ng-show="noResults">
<i class="glyphicon glyphicon-remove"></i> Endereço não encontrado
</div>
</div>
<div class="form-group">
<label for="citizen_address_zip_code">CEP *</label>
<select id="citizen_address_zip_code" ng-model="citizensCtrl.citizen.address.zip_code"
ng-disabled="!citizensCtrl.citizen.address.public_place.id" class="form-control"
ng-options="zip_code as zip_code.number for zip_code in citizensCtrl.zip_codes" required>
<option value="">CEP</option>
</select>
</div>
<div class="form-group">
<label for="citizen_address_number">Numero *</label>
<input type="text" class="form-control" id="citizen_address_number" placeholder="Numero" ng-model="citizensCtrl.citizen.address.number" required>
</div>
<div class="form-group">
<label for="citizen_address_complement">Complemento</label>
<input type="text" class="form-control" id="citizen_address_complement" placeholder="Complemento" ng-model="citizensCtrl.citizen.address.complement">
</div>
<input type="submit" class="btn btn-primary" value="Criar" />
<input type="reset" class="btn btn-default" ng-click="citizensCtrl.defineCitizen()" value="Limpar Formulário" />
</form>
CSS code
.css-form.ng-submitted .ng-invalid{
border: 1px solid #FA787E;
}
AngularJS controller function
self.createCitizen = function(form){
if(form.$valid){
$http.post(apiUrl + endpoint, self.citizen).then(function(response){
alertsService.add('success', 'Morador criado com sucesso!');
self.defineCitizen();
}, function(error){
alertsService.add('danger', 'Oops.. Alguma coisa deu errado. Contate o administrador.');
});
}else{
alertsService.add('danger', 'Você precisa preencher todos os campos obrigatórios.');
}
};
I used form.$setPristine(); on create function
self.createCitizen = function(form){
if(form.$valid){
$http.post(apiUrl + endpoint, self.citizen).then(function(response){
alertsService.add('success', 'Morador criado com sucesso!');
form.$setPristine();
self.defineCitizen();
}, function(error){
alertsService.add('danger', 'Oops.. Alguma coisa deu errado. Contate o administrador.');
});
}else{
alertsService.add('danger', 'Você precisa preencher todos os campos obrigatórios.');
}
};
It works perfectly for me.
Thank you all