Can I create a personalized datepicker without relying on Angular Material or Bootstrap?

Looking to create a datepicker in Angular without relying on Angular Material or bootstrap, similar to the design shown in this image: https://i.sstatic.net/ujfDI.png

Any ideas on how this can be achieved?

Note: It's a business requirement.

Answer №2

It seems like this is just an exercise, so only a few points will be awarded

To create a calendar, you need to use two *ngFor loops for concatenation

<div class="week" *ngFor="let week of days">
  <div class="day" [class.muted]="!day.isMonth" *ngFor="let day of week">
    {{day.day}}
    </div>
</div>

Here, days is an array [6][7]

The first index of the array ranges from 0 to 5 and the second from 0 to 6

Two auxiliary functions can be used:

  private getIncrement(year: number, month: number): number {
    let date = new Date("" + year + "-" + month + "-1");
    let increment = date.getDay() > 0 ? date.getDay() - 2 : 5;
    return increment;
  }

  private getDate(
    week: number,
    dayWeek: number,
    year: number,
    month: number,
    increment: number
  ) {
    let date: any;
    let day = week * 7 + dayWeek - increment;
    if (day <= 0) {
      let fechaAuxiliar = new Date("" + year + "-" + month + "-1");
      date = new Date(
        fechaAuxiliar.getTime() + (day - 1) * 24 * 60 * 60 * 1000
      );
    } else {
      date = new Date("" + year + "-" + month + "-" + day);
      if (isNaN(date.getTime())) {
        let fechaAuxiliar = new Date("" + year + "-" + month + "-1");
        date = new Date(
          fechaAuxiliar.getTime() + (day -1) * 24 * 60 * 60 * 1000
        );
      }
    }
      return {
        date:date,
        day:date.getDate(),
        isMonth:date.getMonth()==month-1
      };
  }
}

After determining the increment based on the month and year, proceed to create the formArray for the days

private generateDays(year:number,month:number)
{
  const increment=this.getIncrement(year,month)
  const days=[];
  [0,1,2,3,4,5].forEach((x,index)=>
  {
    days.push([])
    for (let y=0;y<7;y++){
      days[index].push(this.getDate(x,y,year,month,increment))
    }
  })
  return days
}

Update: Here's a link to StackBlitz

Update 23-april-2020: Correction made when changing the month

NOTE: This code snippet demonstrates how to create a basic calendar. Additional functionality such as making specific dates visible or marking selected days needs to be implemented separately in your HTML structure.

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

show an HTML webpage within a <div> container using AJAX technology

I am trying to include an HTML page named Introduction.html (located in the same folder as x.html) within div1. However, it does not seem to be loading properly. Below is a snippet of the code from x.html x.html <!DOCTYPE html> <h ...

Does anyone have a solution for avoiding the need to generate an HTML character code for displaying Time?

Is there a workaround for generating an HTML character code that resembles Time? Perhaps manipulating another character code to create a similar effect, or utilizing a font with symbols suitable for representing time. ...

What is the process for translating symbols in a URL or text into hexadecimal characters? (e.g. changing = to %3D)

Currently, my script in use is extracting variables from URL parameters using jQuery. The value it retrieves happens to be a URL. For instance, if the URL is as follows: http://localhost/index.html?url=http://www.example.com/index.php?something=some the ...

In IE, Angular Material dialogs close by moving to the top left corner of the page

Whenever a user clicks on the submit button, a confirmation modal pops up on the screen. The modal provides an option for the user to close it by clicking on a button. Here's a snippet of how it's implemented: HTML: <ng-template #confirmMod ...

Incorporating two components and nesting one within the other, similar to the way angular-material seamlessly integrates its components

I recently discovered the angular-material module and I'm a bit perplexed about how it allows multiple components to be used inside one another in the same place. Take a look at the example below: <mat-drawer-container class="example-container"> ...

The hover functionality for the cursor's pointer is malfunctioning

I currently have two div elements in my HTML code: <div id="hm-sp-lenovo-wr"> ....... <div id="hm-sp-motorola-wr"> ....... In my stylesheet, I have defined the following CSS rules: #hm-sp-lenovo-wr:hover { cursor: pointer } #hm-sp-motorol ...

Why am I unable to retrieve data using jQuery and PHP?

I'm working with a PHP form that involves checkboxes: <form action="" method="post" id="CheckBoxForm"> foreach ( $results as $result ) : <input type="checkbox" class="chk" id="check_list[]" value="'.($result->meta_value).&a ...

The Impreza theme is experiencing difficulty displaying Font Awesome icons

Recently, I had a client who needed a WordPress website. After working on the project on my own server, I finally completed it and transferred the entire site to the client's main domain at gulugalmarketing.com. Everything was functioning perfectly o ...

Examining a V-If using Jest for unit testing

How can I effectively test the v-if condition in my parent component using Jest? Parent Component: <div class="systemIsUp" v-if="systemStatus == true"> foo </div> <div class="systemIsDown" v-e ...

Having trouble with finding the correct object in an array of objects using indexOf and splice()?

Here is an example of an array of objects: "followers": [ { "id": "1be87842-2f7f-4e3b-8fde-9a998feb3a01", "bug_id": "4ae2707b-07ef-4e07-95da-77855c67fece", "user_id": "e9e81aa2-4994-483d-a3a7-3b88491f1fda", ...

Is casterror occurring when using findByIdAndRemove?

app.post("/delete", function (req, res) { const checkedItemId = req.body.checkbox; console.log(checkedItemId); Item.findByIdAndRemove(checkedItemId, function (err) { if (!err) { console.log("successf ...

React function does not provide a return value

In my function, I am calculating the current sum of elements. Within my Api, there is a method called Getcoin that works correctly when I log each element during the foreach cycle. However, I am not getting any results in the return statement or console.lo ...

Merging the `on('click')` event with `$(this)`

Hello everyone, this is my first time posting here. I have a question regarding the possibility of achieving a specific functionality. I would like to attach click events to a series of anchor links and then use the $.get() method to reload some icons. T ...

Utilize try-catch or async-await within useEffect when testing with Jest

I am currently setting up my initial unit tests using JEST. I've installed Jest Fetch Mock but unfortunately, I keep encountering an error stating "The promise rejected with reason FetchError". After doing some research, it seems like I may need to i ...

md- The datePicker component consistently encounters errors with Date instances

I encountered an issue where the error message The ng-model for md-datepicker must be a Date instance. Currently the model is a: string appeared. I am utilizing moment.js library to handle dates. Within the view section: <md-datepicker ng-model="Model ...

Error: The value of 'id' cannot be assigned to an undefined property

Recently, I've been delving into learning JS Express and decided to create a basic solution to handle GET / DELETE / POST / PUT requests. Everything was running smoothly until I encountered an issue with the POST router. Below is the code snippet for ...

What is the best way to utilize the "useRouter" function to extract parameters from the URL within the getServerSideProps() method in Next.js?

How can I access the URL parameters within the getServerSideProps() method? Below is the snippet of my code. The objective of my code is to extract parameters from the URL, fetch data from the API, and render it on the front end. import { useRouter } from ...

The div's height is failing to adjust based on the content it contains

My div with the class .list-holder in the header is not adjusting its size based on the content within the div. When I increase the padding of the list items, the content overflows outside the div. I have included the Bootstrap CDN. .list-holder { ...

Is there a way to store a value in an environment variable right after creating it?

In my React application, I have set an environment variable in my .env file and I need to save a value to it later on. REACT_APP_ID_USERLOGGED="" Here is a snippet of code where I attempt to save an ID: process.env.REACT_APP_ID_USERLOGGED = res. ...

Is it possible to achieve two-way data binding across various components in Angular 2?

Currently, I am facing an issue with two components in my Angular project - HomePageComponent and StudentResultsComponent. The problem arises when I type something in the input field of HomePageComponent; the value is not updating in the StudentResultsComp ...