Establish a default value for ng2-datepicker

Has anyone figured out how to set an initial value for the ng2-datepicker when using it for available date and date expires? I want the initial value of dateAvailable to be today's date and the initial value of dateExpires to be 2099-12-31.

<label>Date Available:</label>
<div>
  <ng2-datepicker name="dateAvailable" [(ngModel)]="dateAvailable" [ngModelOptions]="{standalone: true}">  </ng2-datepicker>
</div>
<label>Date Expires:</label>
<div>
  <ng2-datepicker name="dateExpires" [(ngModel)]="dateExpires" [ngModelOptions]="{standalone: true}">  </ng2-datepicker>
</div>

Component

private today = new Date(); 
private dd: any  = this.today.getDate(); 
private mm: any = this.today.getMonth() +1; 
private year: any = this.today.getFullYear(); 

public sop: Sop;
public dateExpires: any; 
public dateAvailable: any;

ngOnInit() {
    if (this.dd<10) {
       this.dd ='0'+this.dd; 
    }
    if(this.mm<10){
       this.mm='0'+this.mm;
    }
    this.sop = {
      description: "",
      country: [this.countrys[4].value],
      storeType: [this.storeTypes[4].value],
      scoType: [this.scoTypes[6].value],
      audience: [this.audiences[2].value],
      sopType: [this.sopTypes[2].value],
      dateAvailable: this.year +'-'+this.mm+'-'+this.dd,
      dateExpires: "2099-12-31"
    }
}

Interface

export interface Sop {
    description: String; 
    country?: String[];
    storeType?: String[]; 
    scoType?: String[]; 
    audience?: String[]; 
    sopType?: String[];
    dateAvailable: any; 
    dateExpires: any;
}

Answer №1

You may also employ the following method:

  1. Begin by importing DatePickerOptions from ng2-datepicker

import { DatePickerOptions} from 'ng2-datepicker';

  1. Next, define a variable : public dateOptions: DateOptions;

  2. and set its value within the ngOnit method : ngOnInit() {

    this.datepickerOptions = new DatePickerOptions({
        format: 'DD-MM-YYYY'
    });
    
  3. Utilize it in your HTML : < ng2-datepicker name="dateExpires" [options]="datepickerOptions ">

Answer №2

To set the initial value, make sure to utilize [options]

<ng2-datepicker name="dateSelection" [(ngModel)]="dateSelection" [options]="{defaultDate: dateSelection}"></ng2-datepicker>

Start by initializing the options

ngOnInit() {
   this.dateSelection = moment("2100-01-01");
}

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

Invoking event emitter within a promise in Angular 2

My event emitter is not functioning properly within a promise's then method. No errors are being generated, it just won't execute. In the child component: @Output() isLoggingIn = new EventEmitter<boolean>(); onLogin() { this.isLoggingI ...

Different and Basic Designs for mat-table

Is there a way to customize the appearance of the material data table (mat-table) beyond the pre-built themes? I'm specifically interested in styles like table-striped, table-sm, or table-bordered from bootstrap 4. Is it possible to apply these style ...

An issue with the HTTP GET Request method is that it often sends "?" instead of "/"

I have a general method for interacting with my Swagger API: get<ReturnType>(url: string, params?: HttpParams): Observable<ReturnType> { return this.http.get<ReturnType>(environment.apiUrl + url, { params: params, }); } ...

Guide to Subscribing to a nested observable with mergeMap within a button's click event

The issue arises in the "addToWishlist" function as I attempt to concatenate the result of the outer observable with the inner observable array and then call the next method on the inner observable. The "addToWishlist" method is triggered by the click ha ...

Unveiling the secrets of the Google Region Lookup API

I am struggling to incorporate the Region Area Lookup feature from Google Maps into my project. Despite it being an experimental feature, I am having difficulty getting it to function correctly. Initially, I attempted to integrate this feature into a Reac ...

Angular's Async Pipe displaying outdated data

I am encountering an issue with my Angular async pipe setup. Here is the code snippet: <ng-container *ngIf="showProjects && (projects | async) as projectList; else loading"> In my projects.page.ts file, I have the following funct ...

Rotate the mat-select arrow when the dropdown opens (moving in both upward and downward directions)

Currently, I have a mat-select dropdown icon arrow that toggles facing up or down based on user clicks. However, after selecting an option and closing the dropdown, the arrow remains in the upward position unless further clicked and held. I have attempted ...

Creating a list of components for drag and drop with Angular CDK is a straightforward process that involves following

I am attempting to use Angular's CDK drag and drop functionality to create a list of components that can be rearranged. However, I am encountering an issue where the components are not being displayed correctly. In my App.component.ts file: impo ...

I keep seeing "Uncaught TypeError: Unable to retrieve property 'get' from undefined" error message popping up

Currently, I am attempting to retrieve a JSON from a separate microservice (local) utilizing a different port. There is uncertainty as to whether the issue lies within my configuration or the microservice itself. Despite successfully displaying the JSON on ...

The type does not meet the requirements set by the class it is inheriting from

Currently, I am in the process of working on a WebSocket Secure (WSS) server utilizing the Node ws library which can be found here. More specifically, I am following the approach outlined in this particular question, although its relevance is yet to be det ...

Using Angular, you can incorporate a dynamic href inside interpolation by using

Looking for a way to include a redirecting link within the response of string interpolation. I am incorporating the API response value into the interpolation binding. For instance, if my response is, "This site is not working. please contact google f ...

A guide on how to efficiently update and submit a reactive form with a single click of the submit button in Angular

Currently, I have a view component setup where clicking the edit button directs me to the register component for form updates using patchvalue. The issue that I am facing is that when I update and register the form using the same button, it creates anothe ...

Retrieve the 90 days leading up to the current date using JavaScript

I've been searching for a way to create an array of the 90 days before today, but I haven't found a solution on StackOverflow or Google. const now = new Date(); const daysBefore = now.setDate(priorDate.getDate() - 90); The result I'm looki ...

Tips for boosting ViteJs development mode performance

One issue I am facing is the slow server performance during development mode. After starting the server and opening the page in my browser, I have to wait 3–6 minutes for it to load! Initially, ViteJs downloads a small amount of resources, but then the ...

Could this be a problem within my recursive function?

Struggling to iterate through a stack of HTML Elements, I attempted to write a recursive function with no success. In the code snippet below, I'm facing challenges in returning a value from an if statement and ultimately from the function itself. Wh ...

An issue with the "req" parameter in Middleware.ts: - No compatible overload found for this call

Currently, I am utilizing the following dependencies: "next": "14.1.0", "next-auth": "^5.0.0-beta.11", "next-themes": "^0.2.1", In my project directory's root, there exists a file named midd ...

How can we effectively implement alert notifications for validating image sizes and formats prior to uploading?

code playground : https://codesandbox.io/s/quizzical-lamport-ql5ep I'm encountering an issue with the code provided in the CodeSandbox link. https://i.sstatic.net/xg3aK.png I've attempted to resolve this issue using various methods, but unfortu ...

Combine an array of objects that are dynamically created into a single object

Having trouble transforming the JSON below into the desired JSON format using JavaScript. Current JSON: { "furniture": { "matter": [ { "matter1": "Matter 1 value" }, { "matter2": "Matter 2 value" }, { ...

Choosing options using an enum in Angular 2

In my TypeScript code, I have defined an enum called CountryCodeEnum which contains the values for France and Belgium. export enum CountryCodeEnum { France = 1, Belgium = 2 } Now, I need to create a dropdown menu in my form using this enum. Each ...

Utilize *ngIf to conceal a row within a material table

I'm struggling with hiding a row after clicking a button in the mat-table. I can't figure out where to place the *ngIf directive. I attempted using it on ng-container, but it didn't work as expected. Below is the excerpt from my HTML file. ...