/ / Angular 4 Forma reactiva Fecha no vinculante - angular, angular2-formas

Angular 4 Forma reactiva Fecha no vinculante - angular, angular2-formas

Estoy tratando de publicar datos en APi web usandomyDatePicker pero el problema es que está enviando un objeto complejo en lugar de solo Date, que la API web no puede leer, mientras que es lo contrario cuando se trata de recuperar los datos, recibe la fecha formateada JSON y la muestra perfectamente.

si intento usar input type = "text", envíalos datos a la perfección y también la API web puede buscarlo y almacenarlo en la base de datos, pero no lo vincula durante la recuperación, aquí está mi código, por cierto estoy usando Angular 4. y .net web api como back-end.

`
<div class="panel panel-primary">
<div class="panel-heading">
{{pageTitle}}
</div>

<div class="panel-body">
<form class="form-horizontal"
novalidate
(ngSubmit)="saveDetails()"
[formGroup]="registrationForm" >
<fieldset>
<div class="form-group" >
<label class="col-md-2 control-label" for="firstNameId">Name</label>

<div class="col-md-8">
<input class="form-control"
id="NameId"
type="text"
placeholder="Name (required)"
formControlName="Name" />
</div>

</div>

<div class="form-group" >
<label class="col-md-2 control-label" for="lastNameId">SurName</label>

<div class="col-md-8">
<input class="form-control"
id="surNameId"
type="text"
placeholder="Sur Name"
formControlName="SurName" />
</div>
</div>

<div class="form-group" >
<label class="col-md-2 control-label" for="countryID">Country</label>
<!-- [formControl]="registrationForm.controls["countryID"]" -->
<div class="col-md-8">
<select class="form-control" formControlName="countryID">
<option value="0" >--Select--</option>
<option *ngFor="let cont of country"
value={{cont.cid}}  >
{{cont.CName}}
</option>
</select>
</div>
</div>

<div class="form-group" >
<label class="col-md-2 control-label" for="Dob">Date of Birth</label>

<div class="col-md-8">
<!-- <my-date-picker name="mydate" [options]="myDatePickerOptions"
formControlName="Dob"
(dateChanged)="onDateChanged($event)"
></my-date-picker> -->

<input type="date" class="form-control" formControlName="Dob" />
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label" for="gender">Gender</label>
<div class="radio col-md-2">
<label><input type="radio" formControlName="gender"  value="male" >Male</label>
</div>
<div class="radio col-md-2">
<label><input type="radio" formControlName="gender"  value="female">Female</label>
</div>
</div>

<div class="form-group" >
<label class="col-md-2 control-label" for="firstNameId">Address</label>
<div class="col-md-8">
<input class="form-control"
id="addressId"
type="text"
placeholder="address"
formControlName="Address" />
</div>
</div>

<div class="form-group">
<div class="col-md-4 col-md-offset-2">
<span>
<button class="btn btn-primary"
type="submit"
style="width:80px;margin-right:10px"
[disabled]="!registrationForm.valid"
>
Save
</button>

</span>
</div>
</div>
</fieldset>
</form>
<div class="has-error" *ngIf="errorMessage">{{errorMessage}}</div>
</div>

import { Component , OnInit } from "@angular/core";
import { FormBuilder,FormControlName,Validators,FormGroup } from "@angular/forms";

import { ActivatedRoute, Router } from "@angular/router";

import { Observable } from "rxjs/Observable";
import { Subscription } from "rxjs/Subscription";

import { IRegistration } from "./reg";
import { ICountry } from "./country";


import {IMyDpOptions , IMyDateModel} from "mydatepicker";

import { RegistrationService } from "./registration.service";

@Component({
selector: "reg-form",
templateUrl: "app/registration-form.component.html"
})
export class RegistrationFormComponent implements OnInit {
country : ICountry[]; // this is used to loop countries
registrationForm: FormGroup;
registration : IRegistration;
private sub: Subscription;
pageTitle: string;

constructor( private registrationService: RegistrationService,
private route: ActivatedRoute,
private router: Router,
private formBuilder: FormBuilder ){}

ngOnInit(): void{
this.registrationForm = this.formBuilder.group({
Name: ["",Validators.required],
SurName: ["",Validators.required],
countryID: ["",Validators.required],
Dob: [null],
gender: ["",Validators.required],
Address: ["",Validators.required]
});
//  this.getCountry();
this.sub = this.route.params.subscribe(
paramns => {
let id = +paramns["id"]; // this +paramns["id"] will convert id from string to integer
this.getRegistration(id);
}
)
}

public myDatePickerOptions: IMyDpOptions = {
dateFormat: "dd/mm/yyyy",

};
getRegistration(id: number): void{

this.getCountry();
this.registrationService.getRegistration(id)
.subscribe((reg: IRegistration) => this.onRegistrationRetrieved(reg));
}
onRegistrationRetrieved(reg: IRegistration) : void{
if(this.registrationForm){
this.registrationForm.reset();
}

this.registration = reg;
if(this.registration.id === 0){
this.pageTitle = "New Registration";
}else{
this.pageTitle = "Edit Registration Detail";
}

var a = new Date(this.registration.Dob);
var d = a.getDate()+"-"+ a.getMonth()+ "-"+ a.getFullYear();

// alert(a);
if(this.registration.id !== 0){
// Important Note:- FormName (Properties name) must be same..
this.registrationForm.patchValue({
Name: this.registration.Name,
SurName: this.registration.SurName,
Address: this.registration.Address,
gender : this.registration.gender,
countryID: this.registration.countryID,
Dob : { date:{ year:a.getFullYear(), month: a.getMonth(), day: a.getDate() } }
});
}

}
getCountry(){
this.registrationService.getCountries().subscribe
((cont: ICountry[])=> this.country = cont);
}

saveDetails(){

if(this.registrationForm.dirty && this.registrationForm.valid){
let p = Object.assign({},this.registration,this.registrationForm.value);
this.registrationService.saveRegistration(p)
.subscribe(
() => this.onSaveComplete()
);
}
}
onSaveComplete(){
this.registrationForm.reset();
this.router.navigate(["List"]);
}

`

este es el resultado cuando envío datos usando datepicker lo he registrado

`
{"Name":"Sean","SurName":"Tom","countryID":"3","Dob":{"date":{"year":2017,"month":9,"day":5},"jsdate":"2017-09-04T18:30:00.000Z","formatted":"05/09/2017","epoc":1504549800},"gender":"male","Address":"saa"}
`

he usado este DatePicker https://github.com/kekeh/mydatepicker

amablemente ayúdame,

Respuestas

1 para la respuesta № 1

Convertiría la fecha del formato de myDatepicker a un formato de fecha normal al guardar:

saveDetails(){
if(this.registrationForm.dirty && this.registrationForm.valid){
let myDateObj = this.registrationForm.value.Dob.date;

// myDatepicker uses kind of a non-standard format,
// hence the strange conversion required
let convertedDate =  new Date(
myDateObj.year,
myDateObj.month-1,
myDateObj.day);

let p = Object.assign({},this.registration,this.registrationForm.value, {
Dob: convertedDate
});
this.registrationService.saveRegistration(p)
.subscribe(
() => this.onSaveComplete()
);
}
}