Issue with default date not functioning in Primeng's p-calendar module

I'm having trouble setting a default date in the datepicker. I attempted to use the defaultDate property of p-calendar, here's what I did:

<p-calendar placeholder="mm/dd/yyyy"
name="deadline" 
required 
[(ngModel)]="deadline" 
#deadline="ngModel" 
[showIcon]="true" 
showTime="showTime" 
hourFormat="12"
[defaultDate]="defaultDate">

Here's my Component.ts code:

public defaultDate: Date = new Date();
ngOnInit() {
    this.defaultDate.setDate(this.defaultDate.getDate() - 5);
}

Unfortunately, the above solution isn't working as expected. Can anyone provide assistance with this issue?

Answer №1

//deadline: Date = new Date(0);
deadline: Date;
defaultDate: Date = new Date("January 31 1980 12:30");

ngOnInit() {
   //if (this.deadline == undefined)
   //    this.deadline = new Date("June 30 1966 12:30");
}

As highlighted in the reported problem, the defaultDate property is meant to display the month and year when the field is first opened without any value.

It's important to note that defaultDate should not be used to set a specific date; it is only intended for scenarios where the ngModel is empty. To establish the initial displayed date, consider using ngModel instead of defaultDate.

Answer №2

For effective binding with your default date, it is recommended to utilize ngModel as explained in the following link: Open Link

In your specific scenario, the code snippet below should be sufficient:

<p-calendar placeholder="mm/dd/yyyy"
name="deadline" 
required 
[(ngModel)]="deadline" 
#deadline="ngModel" 
[showIcon]="true" 
showTime="showTime" 
hourFormat="12"
[defaultDate]=deadline>

For further insights, please consult the calendar.ts file within Primeng's github repository: https://github.com/primefaces/primeng/blob/master/src/app/components/calendar/calendar.ts

Answer №3

Here is the code snippet I used in my project:

<p-calendar [dateFormat]="'dd/mm/yy'" [maxDate]="minDate" [defaultDate]="minDate" [(ngModel)]="date" [iconDisplay]="'input'" [showIcon]="true"  placeholder="JJ/MM/YYYY" id="date" ></p-calendar>

This is the TypeScript code I used to handle the date input:

export class DateFormPageComponent {
  date: Date | undefined;
  currentDate = new Date();
  minDate :Date = new Date(this.currentDate.getFullYear()-13, this.currentDate.getMonth(), this.currentDate.getDate());

  constructor(private router: Router, private route: ActivatedRoute) {
  }
}

Answer №4

give this a shot

let expiryDate: Date;
ngOnInit() {
    this.expiryDate.setDate((new Date()).getDate() - 7);
}

Answer №5

When it comes to the [defaultDate] attribute, make sure you are using JavaScript Date instances. I encountered some difficulties when trying to use a getter method with defaultDate. It's important to note that your component property should be directly linked to defaultDate—avoid using getters, observables, or pipes as they may lead to complications.

In previous versions of PrimeNG, getters functioned properly with defaultDate. However, in the most recent version, a direct property from the component is now required.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to establish a boundary for the forEach function in TypeScript?

In my web-based game, I use the forEach command to retrieve the team players in the lobby. However, for a specific feature in my game, I need to extract the id of the first player from the opposing team. How can I modify my current code to achieve this? T ...

In the Safari browser, an error occurred when trying to locate the variable Tmpo, which is a plain JavaScript class

I created a small Angular application that utilizes a basic JavaScript class located in my assets/js directory. Everything functions flawlessly in my local environment when using ng-serve. However, upon building and deploying the app (ng build --prod), I e ...

Attempting to install angular-in-memory-web-api using npm, but encountering various errors in the process

When trying to install angular-in-memory-web-api using npm, an error with code ERESOLVE occurred. The dependency tree could not be resolved, causing a conflict. While resolving dependencies for the project, it was found that @angular/common version ~13. ...

I'm having trouble resolving this issue with an Unexpected Application Error! It seems that I cannot set the property value of #<TextFieldBase2> since it only has a

Currently, I'm utilizing TypeScript, React Hook Form, Yup validation, and Fluent UI. Every time I attempt to submit a form, I encounter the error 'Unexpected Application Error! Cannot set property value of # which has only a getter'. https:/ ...

Trigger a click event on a third-party webpage that is embedded within an Angular application

In the process of developing my angular application, I found a need to incorporate a graph visualization tool. To achieve this, I utilized the HTML <embed> tag and successfully integrated the graph into my application. Now, my objective is to enable ...

VueJs with typescript encounters issues with recursive child components, resulting in a warning stating "Unknown custom element" being thrown

I am currently working on a dynamic form that is generated by a DataTypeObject (dto). I have encountered an issue with a warning message while creating recursive components. This warning points to a list of components with the same type as their parent: ...

How can TypeScript be forced to output a specific data type?

I've created a generic "fetcher" function that is designed to handle different types of entities. However, I'm encountering an issue where TypeScript is inferring the return type based on all possible conditions within the function. Is there a w ...

Tips for Validating Radio Buttons in Angular Reactive Forms and Displaying Error Messages upon Submission

Objective: Ensure that the radio buttons are mandatory. Challenge: The element mat-error and its content are being displayed immediately, even before the form is submitted. It should only show up when the user tries to submit the form. I attempted to use ...

NextJS - The server attempted to execute the find() function, which is only available on the client side

When attempting to utilize the .find method within the server component, I encounter an error. export async function TransactionList() { const transactions = await fetch('/transactions'); return ( <ul> {transactions.m ...

Difficulty encountered while managing dropdown functionality in Protractor using TypeScript

I'm encountering some difficulties when it comes to selecting a dropdown in Protractor. Here's the structure of my DOM: https://i.stack.imgur.com/qK8sT.png This is the XPath I'm using to select the dropdown with the value "Yes": //label[ ...

Combine Rest API with JSON into BPMN for React or Angular 8 along with TypeScript compatibility

Looking for an angular or react BPMN library that supports TypeScript and REST API services without needing to parse XML. I've searched extensively but can't find a BPMN library with JSON service. I need to create a workflow similar to this us ...

Have there been any instances of combining AngularJS, ASP.NET-WebApi, OData, Breeze.js, and Typescript?

I am attempting to combine different technologies, but I am facing challenges as the entity framework meta-datas are not being consumed properly by breeze.js. Despite setting up all configurations, it's proving to be a bit tricky since there are no ex ...

Having trouble resolving modules with Angular 2 and ASP.NET 5 (unable to locate angular2/core)?

I am diving into a fresh ASP.NET5/MVC6 project and facing some challenges along the way. Struggle 1 When I opt for classic as the moduleResolution in my tsconfig.json, I encounter an error stating: Cannot locate module 'angular2/core' Strugg ...

Sending an object between two components without a direct parent-child connection

Hello, I have a question similar to the one asked on Stack Overflow regarding passing a value from one Angular 2 component to another without a parent-child relationship. In my scenario, Component1 subscribes to a service that makes a GET request to the ...

activeStyle is not a valid property for type 'IntrinsicAttributes'

I encountered an issue while attempting to utilize NavLink in a react typescript project. The error message states: "Property 'activeStyle' does not exist on type 'IntrinsicAttributes & NavLinkProps & RefAttributes'." import Rea ...

Navigating to a specific router outlet in Angular programmatically - Tips for changing routes in a TypeScript file

I am encountering an issue with my side navigation and the named router outlet within it. Specifically, I am attempting to assign the "aside" named router outlet to a sub component called "top-words-aside", but it seems unable to locate the URL segment. r ...

Refresh the Angular component following updates to the store

Working with NGRX/Redux for the first time, I am puzzled by why my component fails to update after adding a new item to an array in the store. Within my main component, these properties are defined: productLines$: Observable<ProductionLine[]>; produ ...

Populate choices in the mat-select dropdown

I am encountering an issue with two-way binding in the mat-select component from Angular Material. In my TypeScript file, I have an option list and a variable for binding called valueFromDB. When I choose a value in the mat-select component, it automatical ...

Unable to retrieve JSON data from php script, but able to successfully retrieve it from file.json

This is the function of my PHP testing script: $json = array ( "age" => 5, "name" => "Lee", ); $json = json_encode($json); echo $json; The JSON data is successfully printed out. When I save its content in a file named file.json and read ...

Encountering a 404 error when importing http/server in deno

The file named index.ts is located below import { serve } from "https://deno.land/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b0c3c4d4f0809e8186869e80">[email protected]</a>/http/server.ts"; function ...