Controlling CSS Styles in Angular using TypeScript

Currently, I am working on an Angular project that involves dynamically populating a calendar. In addition to this, I have a range of dates and the task at hand is to modify the background for specific days within this date range. To manage dates effectively, I am utilizing Moment.js for date handling and Moment Range for managing date ranges.

In TypeScript, I have successfully implemented a function to check if a particular day falls within the specified date range.

const a = new Date(2023,0,8);
const start = new Date(2023, 0, 9);
const end   = new Date(2023, 4, 23);
const range = moment.range(start, end);
console.log(range.contains(a));

Nevertheless, when it comes to the HTML section, there is only one 'day' element that is constantly changing. I have a CSS class called class="background", which alters the background when applied in HTML. However, the challenge lies in accessing specific days accurately. How can I selectively highlight the days falling within the established range?

Typescript file snippet:

export class CalendarComponent implements OnInit {
  week: any = [
    "Mo",
    "Tu",
    "We",
    "Th",
    "Fr",
    "Sa",
    "Su"
  ];

  monthSelect: any[] | undefined;
  dateSelect: any;
  title: string | undefined;
  range: any;

  constructor() {
  }

  ngOnInit(): void {
    this.getDaysFromDate(1, 2023)
  }

  // Function definition continues here...

HTML file snippet:

<div class="wrapper-calendar">
  <div class="header-calendar">
    <div>
      <button (click)="changeMonth(-1)" class="btn-prev"><img src="back.png" alt="back"></button>
    </div>
    <h1>{{dateSelect | date:'MMMM yyyy'}}</h1>
    <div>
      <button (click)="changeMonth(1)" class="btn-next"><img src="forward.png" alt="forward"></button>
    </div>
  </div>

  // HTML structure continues here...

</div>

Answer №1

To enhance the functionality, consider adding an extra property to the day entries. An example implementation could look like the following:

...
 getDaysFromDate(month: number, year: number) {
    ...
    
    this.monthSelect = Object.keys([...Array(numberDays)]).map((a: any) => {
      a = parseInt(a) + 1;
      const dayObject = moment(`${year}-${month}-${a}`);
      return {
        name: dayObject.format("dddd"),
        value: a,
        indexWeek: dayObject.isoWeekday(),
        selected: someFunctionThatReturnsBooleanBasedOnTheSelectionRange(a)
      };
    });
  }
...

The function

someFunctionThatReturnsBooleanBasedOnTheSelectionRange
should ascertain if the day falls within the chosen range. Subsequently, in the HTML markup, include the following:

  <li  [style.gridColumnStart]="first ? day?.indexWeek : 'auto'"
       [ngClass]="{'selected-day-backround': day.selected}"
        *ngFor="let day of monthSelect; let first = first">
      <span> {{day?.value}}</span>
    </li>

Utilizing the ngClass directive enables the addition of custom background styling exclusively to elements within the specified range.

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

What is the best way to transfer PHP form data to an Angular2 application?

As I am still getting familiar with angular2/4, please bear with me if I overlook something obvious. I am currently working on updating a booking process using angular2/4. Initially, the booking procedure commences on a php website, and once some basic in ...

Struggling with Angular CLI installation on Mac?

I've been trying to install Angular on my Mac's global directory, but I haven't been successful after multiple attempts. I've tested the following commands: npm install -g @angular/cli npm install -g @angular/cli@latest How to upgrad ...

Is it more efficient to define a variable or call a method from an object?

Which approach is more effective and why? Option 1: Declaring a variable exampleFunction(requestData: Object) { const username = requestData.username; doSomething(username); } Option 2: Accessing the object property directly exampleFunction(reques ...

Error in Typescript: Function expects two different types as parameters, but one of the types does not have the specified property

There's a function in my code that accepts two types as parameters. handleDragging(e: CustomEvent<SelectionHandleDragEventType | GridHandleDragEventType>) { e.stopPropagation(); const newValue = this.computeValuesFromPosition(e.detail.x ...

What is the process for incorporating TypeScript types into a JavaScript library?

After adding p5 and @types/p5 to my project, I imported p5 in the following way: import * as p5 from 'p5' However, when I tried using p5.createImage(100, 100), I encountered this error message indicating that 'createImage' is not a re ...

Using template references in ViewChildren

I'm facing an issue trying to utilize ViewChildren to create a QueryList from TemplateRef, but I am unable to pass it to the input component. For instance: Component.ts: @ViewChildren(TemplateRef) cellTemplates: QueryList<TemplateRef<any>& ...

Is there a way to keep my fixed footer container from moving while zooming in and out on a webpage

Is there a way to prevent the bottom text from shifting when zoomed in or out on the page? The rest of the content remains stable, but due to using position:absolute for this section to stay at the bottom of another div (content), it causes movement. #con ...

A step-by-step guide on setting up a database connection with .env in typeorm

I encountered an issue while attempting to establish a connection with the database using ormconfig.js and configuring .env files. The error message I received was: Error: connect ECONNREFUSED 127.0.0.1:3000 at TCPConnectWrap.afterConnect [as oncomplete] ( ...

Sequencing API Calls: A Guide on Making Sequential API Requests

Currently, I am working on mastering RxJS. Within my project, there are 3 API calls that need to be made. Specifically, I must execute the 2nd API call and then pass its data as a parameter to the 3rd API call. My attempt at achieving this functionality is ...

Creating an Angular 2 component library that is compatible with both webpack.js and system.js: A guide

This is my first venture into creating an Angular 2 library. So far, it consists of a collection of components. I am aiming to make this library compatible with both Webpack and SystemJS. I have successfully written the code for the first component to be c ...

What is the best way to have dual backgrounds displayed on a single webpage?

Looking to recreate the background design featured on this website: www.zucoffee.com. Does anyone have any tips? In addition, I'm curious about how to achieve that curved separation effect. I understand it involves two divs, but how did they manage t ...

Update breadcrumbs dynamically by clicking on each horizontal panel

I've been dealing with a problem for the past 24 hours. I want to implement a horizontal accordion with breadcrumbs on a webpage. How can I achieve this dynamically, so that when a user clicks on any link in the accordion, the breadcrumbs update simul ...

Exploring Custom Validator Comparisons in Angular

Having trouble comparing two input values in a custom validator. An error should occur if the minValue exceeds the maxValue. FormGroup: sumFormGroup = this.formBuilder.group({ from: ['', [Validators.min(0), sumValidator]], to: [&ap ...

Preventing Component Reuse in Angular 2 RC2 version "2.0.0-rc.2 (2016-06-15)"

During my work with angular 2 RC1 version, I encountered a situation where I needed to implement navigation within nested structures. Specifically, I wanted to be able to navigate from one Component (A) to the same Component (A), but without Angular reusin ...

Error in custom TypeScript: Incorrect error instance detected within the component

I encountered a unique issue with my custom Error export class CustomError extends Error{ constructor(message: string) { super(message); Object.setPrototypeOf(this, CustomError.prototype); this.name = "CustomError"; } Furthermore ...

What are some effective methods for resetting a state in @ngrx/store?

Lately, I've been grappling with a problem that's been on my mind for the past few days. Our team is developing an Angular 2 application, and my task involves creating a wizard for users to complete a form. I've successfully set up the dat ...

Tips for integrating local images into webpack successfully

After creating a library with various UI components, I integrated one component that displays an image based on the image source provided. When incorporating this library into my project, which utilizes webpack and webpack-dev-server, I had to modify the ...

Ways to restrict data types within function parameters

Can you validate types of one argument based on another argument in functions? Consider this example: interface Data { id?: number; name?: string; } let data : Data = {}; // I am unsure how to make the "value" argument strict function update(field : ...

Can someone please tell me the specific HTML entity that Flickr uses for the arrow icons in the action menu?

When viewing an image on FLickr () and clicking on the Actions menu button, a pop-up menu with an arrow icon appears. Interestingly, this icon is not a simple image, but rather a combination of two characters (◢◣). Has anyone been able to determine th ...

The navbar at the top of the page remains in place and obscures

I am facing an issue where my fixed navbar code breaks up into individual boxes for the links when I try to scroll, covering the page title. How can I resolve this? My code is too long to post directly here, so it's available on pastebin at the follow ...