Angular: utilizing input type="date" to set a default value

Looking for a way to filter data by date range using two input fields of type "date"? I need these inputs to already display specific values when the page loads.

The first input should have a value that is seven days prior to today's date, while the second input should display today's date.

Check out my Angular code below:

<input type="date" class="form-control form-date" [(ngModel)]="dtInitial">
<input type="date" class="form-control form-date" [(ngModel)]="dtFinal">

If you can assist me with this, I appreciate it! Thank you in advance.

Answer №1

Make sure the input you provide is a string. Convert the date to a string within your component.

@Component({
  selector: "sample",
  templateUrl: "./app.component.html",
  providers: [DatePipe]
})
export class AppComponent implements OnInit {
  dtStart: string = "";
  dtEnd: string = "";

  constructor(private datePipe: DatePipe) {}

  ngOnInit(): void {
    let currentDay: Date = new Date();
    let oneWeekAgo = new Date();
    oneWeekAgo.setDate(currentDay.getDate()-7)
    this.dtStart = this.datePipe.transform(currentDay, "yyyy-MM-dd");
    this.dtEnd = this.datePipe.transform(oneWeekAgo, "yyyy-MM-dd");
 }
}

Alternatively, you can also utilize the datePipe directly in the template and format the date differently. Various formats are available at this link.

If you wish for the inputs to automatically update when either one changes, you can add this functionality to the component:

 updateStartDate() {
   let newDate = new Date(this.dtStart);
   newDate.setDate(newDate.getDate()-7)
   this.dtEnd = this.datePipe.transform(newDate, "yyyy-MM-dd");
 }

 updateEndDate() {
    let newDate = new Date(this.dtStart);
    newDate.setDate(newDate.getDate()+7)
    this.dtStart = this.datePipe.transform(newDate, "yyyy-MM-dd");
 }

Use the following code for the inputs:

<input (change)="updateStartDate()" type="date" class="form-control form-date" [(ngModel)]="dtStart">       
<input (change)="updateEndDate()" type="date" class="form-control form-date" [(ngModel)]="dtEnd">

This is one approach - consider the implications of two-way binding in your specific scenario :)

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

Step-by-step guide on incorporating an external JavaScript library into an Ionic 3 TypeScript project

As part of a project, I am tasked with creating a custom thermostat app. While I initially wanted to use Ionic for this task, I encountered some difficulty in integrating the provided API into my project. The API.js file contains all the necessary function ...

Observer function simulated by SinonStub

I am currently testing express middleware using sinon.js My goal is to verify that it sends a specific JSON response and prevents the request from moving on to the next middleware or request handler. const middleware = (req: Request, res: Response, nex ...

What is the quickest method for setting up types for node packages?

Whenever I need to use typed packages in my Node.js projects, there are two steps I have to take: Firstly, install the original package. For example: npm install express -S Secondly, install its type definition package. npm install @types/express -D I f ...

Typescript's interface for key-value pairing with generic types

Consider the example Object below: let obj1: Obj = { 'key1': { default: 'hello', fn: (val:string) => val }, 'key2': { default: 123, fn: (val:number) => val }, // this should throw an error, because the types of d ...

What could be the reason behind Next.js attempting to import a non-existent stylesheet?

Lately, I've come across an issue where Nextjs is attempting to import a non-existent stylesheet (refer to the images below). I'm looking for guidance on how to resolve this error. Hoping to find a solution here, thank you Web browser console W ...

Unable to bind input data with interface in Ionic 4 – issues persist

I am working with an interface in Ionic that looks like this: // mydata.model.ts export interface Mydata{ id: string; name: string; date: string } To add new data to the backend, I am binding my data within my component using <ion-input> a ...

Troubleshooting: Angular 13 input radio not recognizing checked condition

Storing selectedKitchenId in localstorage, and checking if selectedKitchenId === kitchen.id to determine which radio button should be selected. Cannot figure out why the checked condition is not working as expected, even though when I use a strong tag to d ...

What to do when the 'image' property in Next.js next/image has an implicit 'any' type and needs fixing?

I'm a newcomer to Next.js and TypeScript and I can't seem to find any helpful resources on resolving this particular issue: import Image from 'next/image'; export default function Item({ image }) { // <-- parameter image needs a &ap ...

This TypeScript error occurs when trying to assign a value of type 'null' to a parameter that expects a type of 'Error | PromiseLike<Error | undefined> | undefined'

Currently, I am making use of the Mobx Persist Store plugin which allows me to store MobX Store data locally. Although the documentation does not provide a TypeScript version, I made modifications to 2 lines of code (one in the readStore function and anot ...

Tips for implementing loading functionality with Interceptor in Angular version 17

I am attempting to implement an interceptor in the latest version of Angular 17. export const loadingInterceptor: HttpInterceptorFn = (req, next,) => { const loadingService = inject(LoadingService); loadingService.show(); return next(req).pipe( finaliz ...

What is the proper way to utilize environment variables on Heroku for my Angular application?

Currently, I am facing difficulties setting up environment variables (or Config Vars in the Heroku world) such as production=true for my angular app on Heroku. I'm struggling to configure the postinstall and build scripts to make use of them effective ...

Signature of the method relies on the method call made earlier

I am currently tasked with implementing a value transformation process that involves multiple steps. To ensure reusability of these steps, a proposed architecture allows for passing steps to the transformation function. For example, transforming a long str ...

What is the reason behind TypeScript enclosing a class within an IIFE (Immediately Invoked Function

Behold the mighty TypeScript class: class Saluter { public static what(): string { return "Greater"; } public target: string; constructor(target: string) { this.target = target; } public salute(): string { ...

The issue arises when attempting to use the search feature in Ionic because friend.toLowerCase is not a valid function

I keep encountering an error message that says "friend.toLowerCase" is not a function when I use Ionic's search function. The unique aspect of my program is that instead of just a list of JSON items, I have a list with 5 properties per item, such as f ...

Primary source for recurring components with the @SkipSelf decorator

Trying to understand the inner workings of Angular's dependency injection system, it seems that the component instance tree is traversed to locate the first occurrence of the specified provider, giving priority to ElementInjector over ModuleInjector ( ...

What is the specific reference of the first parameter in NLS localize?

Regarding the question on localizing VSCode extensions, I am also curious why the localize function requires two parameters. When it comes to localizing settings, it's a simple process of replacing literal values with tokens surrounded by percent sig ...

The seamless union of Vuestic with Typescript

Seeking advice on integrating Typescript into a Vuestic project as a newcomer to Vue and Vuestic. How can I achieve this successfully? Successfully set up a new project using Vuestic CLI with the following commands: vuestic testproj npm install & ...

Error encountered in Typescript when attempting to invoke axios - the call lacks a suitable overload

When I make a call to axios, I include a config object like this: const req = { method, url, timeout: 300000, headers: { 'Content-Type': 'application/json' } } axios(req) An error in TypeScript is thrown stating that "No overload matc ...

webpack is having trouble compiling TypeScript with React components

I've been working on setting up a TypeScript React project with webpack. I followed the TypeScript Tutorial, but I keep running into an error message that says `module parse failed: ... you may need an appropriate loader` Interestingly, I can success ...

Apollo Client's useQuery function is causing unnecessary refetches when using Next.js' router.push method

Currently, I'm facing an issue where a query within a useQuery Apollo Client hook is being re-run unnecessarily every time Next.js's router.push function is triggered. The problem code snippet looks like this: const Parent = () => { useQuery ...