Deactivating upcoming weeks according to the year in Angular 8

In the user interface, there are dropdowns for selecting a year and a week. Once a year is selected, the list of weeks for that year is displayed in the week dropdown.

Now, the requirement is to disable the selection of future weeks.

For example, for the year 2022: The weeks dropdown displays values from 1 to 53. However, users should only be able to select weeks up to the current date in February.

Expected output: Users should not be able to select future weeks; only the numbers for the current weeks should be displayed.

Below is the code that calculates the weeks based on the selected year.

Could someone please assist in implementing the logic to disable future weeks?

week(y = 0) {
    y = y ? y : new Date().getFullYear();
    let d, isLeap;
    d = new Date(y, 0, 1);
    isLeap = new Date(y, 1, 29).getMonth() === 1;
    let count = d.getDay() === 4 || isLeap && d.getDay() === 3 ? 53 : 52;
    this.numbers = Array(count).fill(0).map((x, i) => i + 1);
  }


   

Answer №1

If you're looking to implement the following functionality, consider these steps:

  1. Start by creating a function called getWeekNumberByDate
  2. Retrieve the last week number based on the selected year in the dropdown
  3. Generate an array of week options
  4. Determine the current week number
  5. Apply a condition to disable options where the currentWeekNumber is less than or equal to the item

Let's proceed with the coding.

UPDATED based on feedback

app.component.ts

import { Component } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  public form: FormGroup = new FormGroup({
    year: new FormControl(''),
    week: new FormControl(''),
  });

  public yearOptions = this.getYearOptions();
  public weekOptions = [];
  public currentWeekNumber: number = this.getWeekNumberByDate(new Date());
  public currentYear = new Date().getFullYear();

  onSelectYear() {
    const selectedYear = this.form.value.year;
    this.weekOptions = this.getWeekOptions(selectedYear);
  }

  private getYearOptions() {
    const years = [];
    const fromYear = 2021;
    const toYear = new Date().getFullYear() + 2;

    for (let i = fromYear; i <= toYear; i++) {
      years.push(i);
    }
    return years;
  }

  private getWeekOptions(year: number) {
    const date = new Date();
    date.setFullYear(year);

    const lastDayInYear = new Date(new Date().getFullYear(), 11, 31);
    const lastWeekNumberInYear = this.getWeekNumberByDate(lastDayInYear);

    return Array(lastWeekNumberInYear)
      .fill(0)
      .map((x, i) => ({ weekNumber: i + 1, year: year }));
  }

  /*
   Function source here: 
   https://stackoverflow.com/a/6117889/7979902
  */
  private getWeekNumberByDate(d) {
    d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
    d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay() || 7));
    const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
    const weekNo = Math.ceil(((+d - +yearStart) / 86400000 + 1) / 7);
    return weekNo;
  }
}

app.component.html

<form [formGroup]="form">
  <div class="col-md-3">
    <mat-select
      class="smed-input"
      formControlName="year"
      placeholder="Select SMED Year*"
      (selectionChange)="onSelectYear()"
    >
      <mat-option *ngFor="let year of yearOptions" [value]="year">
        {{ year }}
      </mat-option>
    </mat-select>
  </div>
  <div class="col-md-3">
    <mat-select
      formControlName="week"
      class="smed-input"
      placeholder="Select Week*"
    >
      <mat-option
        *ngFor="let item of weekOptions"
        [value]="item.weekNumber"
        [disabled]="
          currentYear < item.year ||
          (currentYear === item.year && currentWeekNumber < item.weekNumber)
        "
        placeholder="Week Number*"
      >
        {{ item.weekNumber }}
      </mat-option>
    </mat-select>
  </div>
</form>

Link for stackblitz

Updated link for stackblitz

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

Leveraging ternary operators within HTML elements

Currently, I am utilizing the Vue.js framework to create a dynamic list that updates based on two different list objects. My main objective is to adjust the border of the list cards depending on a specific condition. Below are the defined cards: <li ...

Having issues with validating a form using Yup for a Checkbox input?

My form is built using mui, formik, and yup. If the input fields are empty (e.g. "surname") after clicking the submit button, an error is displayed. However, the issue arises when the checkbox for Terms of Service isn't checked as no error shows up. ...

What steps should I take to create code that can generate a JWT token for user authentication and authorization?

I'm struggling to get this working. I have a dilemma with two files: permissionCtrl.js and tokenCtrl.js. My tech stack includes nJWT, Node.js/Express.js, Sequelize & Postgres. The permission file contains a function called hasPermission that is linke ...

Leveraging CSS nth-child selector in conjunction with ngFor in angular2

Looking for a way to style odd and even rows differently in my dynamically generated table using ngFor directive in angular2. *ngIf="AreThereMyOldMessages" *ngFor="let oldm of MyOldMessages;let i=index" *ngIf="AreThereMyNe ...

Is your form complete?

Is there a way to determine if all required fields in the current form are correctly filled in order to disable/enable navigation? Are there any specific properties or JQuery functions that can be used to check for form completion status? ...

Challenges encountered with input outcomes

I am facing an issue with input results. I have a button that triggers a function to check for empty input fields. However, when I click the button, it always falls into the last if statement and displays as if the fields are not empty. I have already att ...

Automatically align a Div to the right within an ngFor directive in an Angular 6 application

<div class="row"> <div class="col-lg-4 col-xs-6" *ngFor="let client of clients;index as i"> <!-- small box --> <div class="small-box bg-dashboard-box" > <div class="inner"> <div class="text-black"> ...

Retrieving data from a <span> element within a webpage created using ReactJS

I am completely new to the world of web design and development, so there may be some mistakes in my request. Essentially, I have a webpage that contains numerous span tags like the following example: These span tags are part of a significantly large DOM t ...

The ".splice()" method continuously removes the final element from an array

I have implemented a function on my form that allows me to add multiple file inputs for various images by clicking a button. Although this functionality is working correctly, I am facing an issue while trying to delete an input field using .splice. Instead ...

I want to know the most effective way to showcase particular information on a separate page using Angular

Recently, I've been working with a mock json file that contains a list of products to be displayed on a Product page. My goal is to select a specific product, such as 'Product 1', and have only that product's information displayed on th ...

Issue with Vue.js: document.querySelector is returning a null value even though the element clearly exists

I'm currently working on implementing a responsive navbar following Kevin Powell's tutorial, but I've run into an issue. For some reason, when I try to select the element with the class 'primary-navigation' using 'const primar ...

Is there a way to enable data-add-back-btn using jQuery script?

Currently, I am utilizing jQuery 1.9.1 and jQuery Mobile 1.3.1 to define multiple pages within my project setup: <div id="q1" data-role="page" data-add-back-btn="false" data-back-btn-text="Home"> <div data-role="header" data-position="fixed" ...

After generating the token, where is the appropriate place to define the authorization header?

I am currently working on implementing a security system based on tokens. The challenge I am facing is determining the appropriate location to set the authorization header after generating it, in order to validate it across all of my different routes. Belo ...

Updating a value in one input field triggers changes in several other input fields in Angular 6

I'm currently in the process of learning the basics of Angular 6 and TypeScript, and I'm struggling to figure out how to achieve a specific functionality. Essentially, I have a field where users can input a numerical value, and based on that inpu ...

Is it possible to generate multiple services from a single factory in Angular?

Recently, I developed a service called tableService using the following code: app.factory('tableService', [function() { var data = some data; var foo = function (){ //do something to data here }; return { data: data, ...

"Unlocking the potential: Exploring the power of keyof with

Currently, I am working with React Redux toolkit and keyof to specify that one element of my action payload should be the key of the type that my state is composed of. This allows me to update the properties of the state using a redux action. However, I am ...

The data from Angular2 Observable Subscription appears undefined, although a closer look at the Browser Debug reveals otherwise

Is it possible there is an issue with the data subscription process? Upon subscribing to data from a service call, 'undefined' is returned as the data set. Surprisingly, when I debug the code in the browser, it clearly shows that the correct dat ...

Setting up a chat feature in a Laravel application: A step-by-step guide

Looking to Enhance My Web-Application I have been working on a web-application that utilizes: Laravel for the back-end Angular for the front-end. Milestone Achieved! I successfully implemented the entire user authentication process including: User Aut ...

In Production mode, Angular automatically reloads the page every time my data request service is executed to fetch data from the API

The Issue at Hand I have developed an angular application that functions flawlessly on the development server. This application utilizes localStorage to store the user's JWT token, although I am aware that this may not be the most secure method. How ...

An error occurred with the authorization headers when attempting to retrieve the requested JSON

I am attempting to retrieve JSON data from the Bing Search API. Here is what I have implemented: <!DOCTYPE html> <html> <body> <p id="demo"></p> <script language="JavaScript" type="text/javascript" src="jquery-1.12.3.js"& ...