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

Leverage Springs with TypeScript

function createDefaultOrder(items: any[]): number[] { return items.map((_, index) => index); } type CustomHandler<T> = (index: number) => T; type CustomValues = { zIndex: number, y: number, scale: number, shadow: number, immediate: ...

Learn the process of automatically including correlation headers in Angular HTTP requests for Application Insights

I am currently utilizing the npm package @microsoft/applicationinsights-web within my Angular project. In my http service, I have custom headers that seem to be overriding the correlation headers ('Request-Id' and 'Request-Context'). D ...

No output returned by SwitchMap in Angular 2

I'm facing an issue with my SwitchMap implementation and struggling to resolve it. The problem occurs when I have a collection of category buttons that, when clicked, trigger a server call to load the corresponding data. However, if I switch between t ...

Updating nested interface values using React hooks

I am looking to develop an application that can seamlessly update a nested configuration file after it has been imported (similar to swagger). To achieve this, I first created a JSON configuration file and then generated corresponding interfaces using the ...

Extending Angular 2 functionality from a parent component

As a continuation of the discussion on Angular2 and class inheritance support here on SO, I have a question: Check out my plunckr example: http://plnkr.co/edit/ihdAJuUcyOj5Ze93BwIQ?p=preview Here is what I am attempting to achieve: I want to implement s ...

Sending an image in the body of an HTTP request using Angular 7

I'm currently in the process of developing an Angular application that captures an image from a webcam every second and sends it to a REST API endpoint for analysis. To achieve this, I have implemented an interval observable that captures video from t ...

Exploring the world of Angular CLI testing and the versatility of

Struggling with integrating Angular CLI's test framework and enum types? When creating an enum like the following (found in someenum.ts): const enum SomeEnum { Val0, Val1 } Utilizing it in this way (in app.component.ts): private someEnum = Some ...

Experiencing a Typescript error when trying to access a property within a nested object

My current challenge involves typing an object, which seems to be error-free until I try to access a nested property and encounter the dreaded red squiggle. After some research, I came across suggestions like this: type FlagValue = string | boolean | numb ...

Using custom types for prop passing in Next.js with TypeScript

After making a http call, I obtain an array containing JSON data. This data is then assigned to a type called Service. type Service = { id?: string; name?: string; description?: string; }; The api call is made in getServerSideProps and the Service type is ...

Discover the process of implementing nested service calls in Angular 2 by utilizing observables

Here are my component file and service file. I am trying to achieve that after the verification() service method is successfully called, I want to trigger another service method signup() within its success callback inside subscribe. However, I am encounter ...

Creating Dynamic Forms in React with Typescript: A Step-by-Step Guide to Adding Form Elements with an onClick Event Handler

I am looking to create a dynamic generation of TextFields and then store their values in an array within the state. Here are my imports: import TextField from '@material-ui/core/TextField'; import Button from '@material-ui/core/Button&apos ...

What is the process for running Protractor in a project that is not using AngularCLI?

I am new to using Protractor and I am eager to run my first test. However, I am facing some difficulties on how to get started. I initially tried entering ng e2e in the cmd prompt but received a message stating that I "have to be inside an Angular CLI proj ...

Ensuring User Authentication in Angular with Firebase: How to Dynamically Hide the Login Link in Navigation Based on User's Login Status

After successfully implementing Angular Firebase email and password registration and login, the next step is to check the user's state in the navigation template. If the user is logged in, I want to hide the login button and register button. I tried s ...

The binding element 'params' is assumed to have a type of 'any' by default

I encountered an issue The binding element 'params' implicitly has an 'any' type. Below is the code snippet in question: export default function Page({ params }) { const { slug } = params; return ( <> <h1>{s ...

Exploring the Augmented Theme in Material UI Using TypeScript and the "keyof" Operator

I've recently started working with TypeScript and I'm facing an issue that I can't seem to solve. Here's the problem: I extended my Material UI theme with the following types: declare module '@material-ui/core/styles/createPalette& ...

Utilizing Angular 4's piping feature to manipulate data sourced from an API observable within

I am currently working on setting up a filter for my stories. After subscribing to the API call, I receive the data in the form of an array of objects. However, I am encountering an error while trying to apply filters. Here is a snippet of relevant inform ...

Is there a way to incorporate the router into the observable within the guard?

Is there a way to inject a router into my guard when I have an Observable method returned? I want to implement routing with a redirect to the login page if a certain condition is met: If the result of the isAccessToLobby method is false, then redirect to t ...

I am experiencing difficulties with *ngIf in my HTML as it is not functioning properly, however, the ng

I have come across many inquiries related to this issue, but none of them proved helpful for me. Below is my HTML code: <div class="pl-lg-4"> <div *ngIf="isStorySelected; else hi" class="row"> ...

Creating an Angular 8 build that can be executed from a subdirectory

As I develop using the standard localhost:4200, I also want to understand how a build works. To achieve this, I made some modifications in the angular.json file. The alteration is as follows: "outputPath": "D:/a_root/dist", The 'a_root' represe ...

Exploring the Yahoo Finance Websocket with Angular

Upon visiting the Yahoo finance website (for example, ), I noticed that the page establishes a WebSocket connection. The URL for this WebSocket is wss://streamer.finance.yahoo.com/ I'm currently working on a small project where I need to retrieve dat ...