4

Error is

InvalidPipeArgument: 'Invalid Date' for pipe 'DatePipe'.

I want display json data in p-calendar (Primeng component). I am fetching data from json file and display in input field but its not working.

If it possible then please provide solution for p-dropdown and p-radiobutton for display json data in input field

demographic.component.html

<form [formGroup]="userform" (ngSubmit)="onSubmit(userform.value)">

<div class="ui-fluid">

    <p-panel header="Demograhics">


        <div class="ui-inputgroup">

                <label for="email" class="ui-md-2 control-label">Birthdate</label>

                    <div class="ui-md-6">
                        <div class="ui-inputgroup">
                            <p-calendar [(ngModel)]="date3" formControlName="birthdate"  [monthNavigator]="true" [defaultDate]="defaultdate" [yearNavigator]="true"   yearRange="1950:2030" [showIcon]="true" dateFormat="dd.mm.yy" name="calendar"></p-calendar> <span style="margin-left:35px">{{date3|date}}</span>       
                        </div>
                    </div>

                    <div class="ui-md-4">     
                        <div class="ui-message ui-messages-error ui-corner-all" *ngIf="!userform.controls['birthdate'].valid&&userform.controls['birthdate'].dirty">
                            <i class="fa fa-close"></i>
                        Birthdate is required
                        </div>                                
                    </div>
        </div>


        <div class="ui-inputgroup">

                <label for="password" class="ui-md-2 control-label">Martial Status</label>

                    <div class="ui-md-6">
                        <div class="ui-inputgroup">
                                <p-dropdown [options]="Martials" formControlName="martialstatus" [(ngModel)]="selectedvalidid5" [style]="{'width':'150px'}" filter="true" name="something" placeholder="MartialStatus">
                                        <ng-template let-item pTemplate="selectedItem">


                                            <span style="vertical-align:middle">{{item.label}}</span>
                                        </ng-template>
                                        <ng-template let-Martial pTemplate="item">
                                            <div class="ui-helper-clearfix" style="position: relative;height: 25px;">

                                                <div style="font-size:14px;float:right;margin-top:4px">{{Martial.label}}</div>
                                            </div>
                                        </ng-template>
                                    </p-dropdown>          


                            </div>
                        </div>

                        <div class="ui-md-4">     
                            <div class="ui-message ui-messages-error ui-corner-all" *ngIf="!userform.controls['martialstatus'].valid&&userform.controls['martialstatus'].dirty">
                                <i class="fa fa-close"></i>
                            Martial status is required
                            </div>


                    </div>
        </div>

        <div class="ui-inputgroup">

                <label for="password" class="ui-md-2 control-label">Gender</label>

                    <div class="ui-md-6">
                        <div class="ui-inputgroup">
                            <p-radioButton name="group2" value="Male" formControlName="gender" label="Male"  [(ngModel)]="val2" inputId="preopt1" name="something"></p-radioButton>
                            <p-radioButton name="group2" value="Female" formControlName="gender" label="Female"  [(ngModel)]="val2" inputId="preopt2" name="something"></p-radioButton>
                        </div>
                    </div>

                    <div class="ui-md-4">     
                        <div class="ui-message ui-messages-error ui-corner-all" *ngIf="!userform.controls['gender'].valid&&userform.controls['gender'].dirty">
                            <i class="fa fa-close"></i>
                        Gender is required
                        </div>


                </div>
        </div>



        <div class="ui-inputgroup">

                <div class="ui-md-8 ui-md-offset-4">
                    <button pButton type="submit" label="Submit" [disabled]="!userform.valid"></button>
                        <button pButton type="button" (click)="count()" label="Cancel"></button>                           
                </div>
        </div>                     

    </p-panel>

</div>

</form>  

demographic.component.ts

import { Component, OnInit } from '@angular/core';
import * as jwt from 'angular2-jwt/angular2-jwt';
import { CardModule } from 'primeng/card';
import { CalendarModule } from 'primeng/calendar';
import { ScrollPanelModule } from 'primeng/scrollpanel';
import { Response } from '@angular/http/src/static_response';
import { CountryService} from './country-list.service';
import {SelectItem} from 'primeng/api';
import { Message } from 'primeng/components/common/api';
import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms';
import { PersonListService,Person, Demographic} from './person-list.service';


@Component({ 
  moduleId: module.id,
  selector: 'sd-demographicform',
  templateUrl: 'demographicform.component.html',
  styleUrls: ['demographicform.component.css']
})
export class DemographicFormComponent implements OnInit {



  date3: Date = new Date("{{ demographics?.Birthdate | date:dd.mm.yy }}");

  dates: Date[];

  rangeDates: Date[];

  minDate: Date;

  maxDate: Date;

  es: any;

  invalidDates: Array<Date>

  val2: string = 'Male';

  val3: string = 'Unmarried';

  text: string;

  ValidIds: SelectItem[];

  selectedvalidid2: string = '';

  Religions: SelectItem[];

  selectedvalidid3: string = '';

  BloodGroups: SelectItem[];

  selectedvalidid4: string = '';

  Martials: SelectItem[];

  selectedvalidid5: string = '';

  country: any;

  filteredCountriesSingle: any[];

  msgs: Message[] = [];

  userform: FormGroup;

  submitted: boolean;

  demographics: Demographic;



  constructor(private countryService: CountryService,private fb: FormBuilder,public personListService:PersonListService) { }

  filterCountrySingle(event) {
      let query = event.query;
      this.countryService.getCountries().then(countries => {
          this.filteredCountriesSingle = this.filterCountry(query, countries);
      });
  }

  filterCountry(query, countries: any[]):any[] {
    //in a real application, make a request to a remote url with the query and return filtered results, for demo we filter at client side
    let filtered : any[] = [];
    for(let i = 0; i < countries.length; i++) {
        let country = countries[i];
        if(country.name.toLowerCase().indexOf(query.toLowerCase()) == 0) {
            filtered.push(country);
        }
    }
    return filtered;
}
  ngOnInit() {

    this.getperson();
    //this.date3.setDate((new Date()).getDate() - 5);
    this.userform = this.fb.group({
        'nationality': new FormControl('', Validators.required),
        'birthdate': new FormControl('', Validators.required),
        'martialstatus': new FormControl('', Validators.required),
        'gender': new FormControl('', Validators.required),
        'height': new FormControl('', Validators.required),
        'valididtype': new FormControl('', Validators.required),
        'valididno': new FormControl('', Validators.required)

    }
);

    this.ValidIds = [
      {label: 'Adharcard', value: 'Adharcard'},
      {label: 'Pancard', value: 'Pancard'},
      {label: 'Driving Lincense', value: 'DrivingLincense'},
      {label: 'Passport', value: 'Passport'},

  ];

  this.Martials = [
    {label: 'Married', value: 'Married'},
    {label: 'Unmarried', value: 'Unmarried'},
    {label: 'Divorced', value: 'Divorced'},
    {label: 'Widowed', value: 'Widowed'},
    {label: 'Separated', value: 'Separated'},
];

  this.Religions = [
    {label: 'Hindu', value: 'Hindu'},
    {label: 'Islam', value: 'Islam'},
    {label: 'Christianity', value: 'Christianity'},
    {label: 'Sikhism', value: 'Sikhism'},
    {label: 'Buddhism', value: 'Buddhism'},
    {label: 'Jainism', value: 'Jainism'},
];

this.BloodGroups = [
  {label: 'A', value: 'A'},
  {label: 'A+', value: 'A+'},
  {label: 'B', value: 'B'},
  {label: 'C', value: 'C'},
  {label: 'AB', value: 'AB'},
  {label: 'O', value: 'O'},

];

       this.es = {
            firstDayOfWeek: 1,
            dayNames: [ "domingo","lunes","martes","miércoles","jueves","viernes","sábado" ],
            dayNamesShort: [ "dom","lun","mar","mié","jue","vie","sáb" ],
            dayNamesMin: [ "D","L","M","X","J","V","S" ],
            monthNames: [ "enero","febrero","marzo","abril","mayo","junio","julio","agosto","septiembre","octubre","noviembre","diciembre" ],
            monthNamesShort: [ "ene","feb","mar","abr","may","jun","jul","ago","sep","oct","nov","dic" ],
            today: 'Hoy',
            clear: 'Borrar'
        }


        let today = new Date();
        let month = today.getMonth();
        let year = today.getFullYear();
        let prevMonth = (month === 0) ? 11 : month -1;
        let prevYear = (prevMonth === 11) ? year - 1 : year;
        let nextMonth = (month === 11) ? 0 : month + 1;
        let nextYear = (nextMonth === 0) ? year + 1 : year;


        let invalidDate = new Date();
        invalidDate.setDate(today.getDate() - 1);
        this.invalidDates = [today,invalidDate];
    }
    getperson(){

        this.personListService.getDemographic()
        .subscribe(
         resp => this.demographics = resp.Demographics,

          //resp => this.addresses = resp.Addresses,

        );


   }
    onSubmit(value: string) {
        this.submitted = true;
        this.msgs = [];
        this.msgs.push({severity:'info', summary:'Success', detail:'Form Submitted'});
    }
}   

person.json

{

"Demographics" : {

            "ProfileId":1,
            "FirstName":"Vinit",
            "LastName":"Mapari",
            "Birthdate":"21/12/1996",
            "MartialStatus":"Unmarried",
            "Gender":"Male",
            "Height":"5ft2inch",
            "ValidIdType":"Pancard",
            "ValidIdNumber":"123",
            "Nationality":"Indian",
            "Religion":"Hindu",
            "BloodGroup":"A",
            "NearestRailwayStation":"Byculla"

        }
} 
James Z
  • 12,209
  • 10
  • 24
  • 44
Vinit Mapari
  • 439
  • 3
  • 7
  • 15

1 Answers1

3

You get the error "InvalidPipeArgument: 'Invalid Date' for pipe 'DatePipe'", because you are trying to format undefined with a DatePipe (and also the syntax is incorrect).

First you have to fetch the data and then assign the date that you received from the response.

You can do.

in the top.

date3: string;

and when you receive the data.

getperson(){

    this.personListService.getDemographic()
    .subscribe(
     resp => {
        this.demographics = resp.Demographics;
        this.date3 = this.datePipe.transform(this.demographics.Birthdate, 'dd.mm.yy');
    });

}

You can check how to make DatePipe in your component work in my other answer.

But also keep in mind that you will have to change the date to ISO standard date (YYYY-MM-DD), before you format it with a DatePipe. If you are just using a json file to store your date, then change it in a json file. If you are using some database, you should already have the iso date, when you receive the data if you have the field and the api handling set up correctly.

Gregor Ojstersek
  • 1,369
  • 7
  • 12
  • Thank you very much.I got this error at this.date3 = this.datePipe.transform(this.demographics.Birthdate, 'dd.mm.yy'); Error is [ts] Argument of type 'string' is not assignable to parameter of type '(error: any) => void' How to convert this?please give me solution – Vinit Mapari Aug 04 '18 at 14:02
  • Since you are formatting date to string. Make date3: string; instead of Date. See working example: https://stackblitz.com/edit/angular-vxsuy4?file=src%2Fapp%2Fapp.component.ts – Gregor Ojstersek Aug 04 '18 at 16:35
  • https://stackoverflow.com/questions/51729637/how-to-disply-data-from-json-in-array-of-address-class-in-contact-form please solve this – Vinit Mapari Aug 07 '18 at 16:26