Harry
Harry

Reputation: 47

Angular 4 Reactive Form Date not binding

I am trying to Post data on Web APi using myDatePicker but the problem is, it is sending a complex object instead of just Date, which the web api cannot read, while its opposite when it comes to retrieving the data, it receives the JSON formatted date and display it perfectly.

if i try using input type="text" then it sends the data perfectly and also web api can fetch it and store it onto database, but it doesn't bind it during the retrieval, here is my code, By the Way i am using Angular 4. and .net web api as backend.

`
<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']);
}

`

this is the output when i send data using datepicker i have logged it

`
{"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"}
`

i have used this DatePicker https://github.com/kekeh/mydatepicker

kindly help me,

Upvotes: 0

Views: 2851

Answers (1)

Eeks33
Eeks33

Reputation: 2315

I would convert the date from myDatepicker's format back to a regular date format upon save:

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()
    );
  }
}

Upvotes: 1

Related Questions