Tips for binding two elements bidirectionally to a single date module

I am working with two date picker elements, one for selecting months and another for selecting years. I want to establish a two-way binding between these elements and a JavaScript Date object. My inquiry is as follows:

Is it feasible to achieve this? If so, what approach should be taken? If not, what alternative methods can be used to simulate this functionality?

Sample code snippet:

<select class="selectpicker form-control" required [(ngModel)]="exp.StartDate.Month" >
   <option *ngFor="let obj of months" [value]="obj">{{obj}}</option>>
</select>


<select class="selectpicker form-control" required [(ngModel)]="exp.StartDate.Year">
   <option *ngFor="let obj of years" [value]="obj">{{obj}}</option>>
</select>

Both selectors receive data in arrays, representing either months (0-11) or years.

Answer №1

To simplify things, you can create a property called fecha with a setter function in your Component:

year:number;
month:number;
get fecha():any
{
    return new Date(this.year,this.month-1,1)
}
console.log(year,month,fecha);

If you are using ngModel, you can separate the [(ngModel)] into:

<select [value] = "exp.StartDate.Month" (input)="updateMonth($event.target.value)" >
...
</select>
<select [value] = "exp.StartDate.Year" (input)="updateYear($event.target.value)">

//In your component
updateMonth(month:number)
  {
    this.exp.StartDate.Month=month;
    this.exp.StartDate.Value=this.exp.StartDate.Year+'-'+this.exp.StartDate.Mont+'-1';
  }
  updateYear(year:number)
  {
    this.exp.StartDate.Year=year;
    this.exp.StartDate.Value=this.exp.StartDate.Year+'-'+this.exp.StartDate.Mont+'-1';
  }

Alternatively, you can implement a custom form control to manage the value. Below is a sample code with a custom form control that expects a JavaScript Date Object (if you are using a String, you may need to modify the code):

import { Component, forwardRef, HostBinding, Input } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

//TODO: Change input to select
@Component({
  selector: 'app-month-year',
  template: `
    <input [disabled]="disabled" [value] = "month" (input)="updateMonth($event.target.value)" >
    <input [disabled]="disabled" [value] = "year" (input)="updateYear($event.target.value)">
  `,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => MonthYearComponent),
      multi: true
    }
  ]
})
export class MonthYearComponent implements ControlValueAccessor {

  month:number;
  year:number;


  // Allow the input to be disabled, and when it is make it somewhat transparent.
  @Input() disabled = false;
  @Input('value') value;

  onChange: any = () => { };
  onTouched: any = () => { };

  updateMonth(month:number)
  {
    this.month=month;
    this.value=this.getDate(); //<--change the "value"
    this.onChange(this.value);
  }
  updateYear(year:number)
  {
    this.year=year;
    this.value=this.getDate(); //change the value
    this.onChange(this.value);

  }

  constructor() { }

  registerOnChange(fn) {
    this.onChange = fn;
  }

  registerOnTouched(fn) { 
    this.onTouched = fn;
  }

  writeValue(value) { //<--when receive a value
    if (value) {
      this.month=value.getMonth()+1;
      this.year=value.getFullYear();

      }

  }
  setDisabledState(isDisabled: boolean): void {
    this.disabled = isDisabled;
  }
  //It's better use a function to return the value
  private getDate() 
  {
    const date=new Date();
    date.setFullYear(this.year,this.month-1,1);
    return date;
  }
}

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

Using a jQuery plugin within an Angular 2 component: A step-by-step guide

Looking to implement an image slider plugin called Vegas only on the home page within my Angular 2 application. The Vegas jQuery plugin has been added via npm and is located under the /node_module directory. The following code snippet shows my home page c ...

Personalizing the mat-checkbox

I'm trying to customize the checked icon in angular material mat-checkbox. Currently, it displays a white tick icon inside a colored background box, but I want to replace the tick with a cross when it is checked. After spending all day searching, I ha ...

When HTMLElement focus is activated, it interrupts the flow of execution

(the code presented is in TypeScript and I'm working with Angular 5, but I don't think that's the issue, so prove me wrong!) I have a basic input field that triggers events in an Angular component. (EDIT: I've added the complete compo ...

Angular2 encountering an unidentified Auth2 Object during logout process

Greetings, I am currently experiencing an issue with signing out of an auth2 client. Previously, this process functioned correctly until I upgraded my router to comply with new RC requirements. Now, it seems that the auth2 object is being cleared or lost ...

Error in TypeScript in VSCode when using the React.forwardRef function in a functional component

We are developing our component library using JavaScript instead of TypeScript. In our project's jsconfig.json file, we have set checkJs: true. All components in our library are functional and not based on class components. Whenever a component needs ...

Is there a way to access URL parameters using a router in Angular 7?

I am facing a challenge with the Angular 7 router in understanding how to utilize the "token" get parameter from different parts of the URL. Below is the code snippet where I have defined multiple routes: const myRoutes: Routes = [ { path: 'register ...

Deploying a nodejs application with angular as the user interface framework using Firebase

Is there a way to set up an express.js application with angular as the front-end framework, multiple route files, and communication between the server and angular via service level API calls, in order to deploy it on firebase using Firebase Hosting? Curre ...

Issue with ng2-charts not rendering properly on the client side when utilized in Angular version 2.0.0-beta-17

Struggling with using ng2-charts in my Angular 2 app and encountering some challenges. app.ts import {Component} from 'angular2/core'; import {CHART_DIRECTIVES} from 'ng2-charts/ng2-charts'; @Component({ selector: & ...

Tips on enlarging the header size in ion-action-sheet within the VueJS framework of Ionic

Recently I started using Vue along with the ionic framework. This is a snippet of code from my application: <ion-action-sheet :is-open="isActionSheetOpen" header="Choose Payment" mode="ios" :buttons="buttons&qu ...

Include baseHref in the sourceLocale configuration of Angular's internationalization feature

In order to set a baseHref for my default language in my Angular code (written in Portuguese), I need to make some adjustments. My goal is to use "ng serve --configuration=pt" to serve angular, and have the router display "http://localhost:4200/pt", simila ...

What are the steps to conduct a vulnerability scan on an Angular/Node application?

I'm in the process of setting up a vulnerability check for my Angular 7/Node project. Can anyone advise on how to effectively run this type of process? Are there any recommended tools available? Initially, I attempted to use the dependency-check-mave ...

Is it possible to merge arrays of angular modules together?

I have a challenge where I am attempting to merge two arrays of ngx modules and export them as a unified array. Here is an example of what I'm trying to achieve: @NgModule({ declarations: [], exports: [ CommonModule, FormsModule, ReactiveForm ...

The database migration encounters an issue: The module 'typeorm' cannot be located

When I run the following commands: ❯ node --version v16.19.0 ❯ yarn --version 3.5.0 I am attempting to launch this project: https://github.com/felipebelinassi/typescript-graphql-boilerplate However, when I execute: yarn db:migrate which runs the c ...

The RXJS subscribe function fails to work when called within an HTML document

I am encountering an issue where an observable is not being invoked from the HTML page. The method works perfectly fine when triggered by angular and displays the desired output. However, when attempting to invoke it through a button, it does not work. ...

What is the process for connecting a global variable to a BehaviorSubject?

I'm currently working on implementing a login feature in my application, and I want specific buttons within the app.component template to only be visible once the user successfully logs in. To achieve this, I am attempting to utilize BehaviorSubject. ...

Issue observed in Angular Material: mat-input does not show background color when in focus mode

https://i.stack.imgur.com/eSODL.png Looking for a solution regarding the mat-input field <mat-form-field> <input class='formulaInput' matInput [(ngModel)]='mathFormulaInput'> </mat-form-field> The blue backg ...

Bootstrap 4 or ngBootstrap: A Comparison

I have a couple of inquiries: Firstly, I am wondering if ngBootstrap is compatible with Angular 4. While I've seen instances on Google where individuals have successfully used Angular 4 with ngBootstrap, the official site mentions dependencies on Ang ...

Using Angular 6 shortcodes in HTML

Is there a way to save an element in HTML as an alias for repeated use in Angular 6 without using *ngIf directive? For instance, consider the following code snippet: <dumb-comp [name]="(someObservable | async).name" [role]="(someObservable | a ...

onmouseleave event stops triggering after blur event

I am facing an issue with a mouseleave event. Initially, when the page loads, the mouseleave event functions correctly. However, after clicking on the searchBar (click event), and then clicking outside of it (blur event), the mouseleave functionality stops ...

Troubleshooting: Angular input binding issue with updating

I am currently facing a challenge with connecting a list to an input object in Angular. I was expecting the updated values to reflect in the child component every time I make changes to the list, but strangely, the initial values remain unchanged on the sc ...