Unlocking the potential of the date-range picker in Material Angular: extracting value between selected dates

Recently, I successfully passed the dates from the component to the template date picker. My current dilemma is figuring out how to retrieve the value from the template (HTML) to the component (TS) file. Here's a snippet of the code:

startDate = new Date() || selected start date from date picker
endDate = new Date(2019, 1, 20) || selected end date form date picker

TypeScript:

export class AppComponent {
  startDate = new Date();
  endDate = new Date(2019, 1, 20);
  form: FormGroup;

  constructor(fb: FormBuilder) {
    this.form = fb.group({
      date: [{begin: this.startDate, end: this.endDate}]
    });
  }
}

HTML:

<form [formGroup]="form">
  <mat-form-field>
    <input matInput 
      placeholder="Choose a date" 
      [satDatepicker]="picker" 
      formControlName="date">
    <sat-datepicker-toggle 
      matSuffix 
      [for]="picker">
    </sat-datepicker-toggle>
    <sat-datepicker 
      #picker 
      [rangeMode]="true" 
      touchUi="true">
    </sat-datepicker>
  </mat-form-field>
</form>

Initially, the date is passed by default, but my challenge lies in capturing the value when a different range is selected. I have attempted using ngModel but failed to retrieve the value from a variable. For reference, you can check out the Stackblitz project link below.

https://stackblitz.com/edit/angular-3gx6xx

Answer №1

In order to retrieve specific dates from the daterangepicker material, you need to utilize the (datesUpdated) API in the template.

Template:

<input ngxDaterangepickerMd (datesUpdated)="datesUpdated($event)"> <input>

Typescript:

datesUpdated(range){
console.log(range.startDate._d);
console.log(range.endDate._d);
}

Answer №2

Simply insert the following code snippet into your constructor:

this.form.get('date').valueChanges
      .subscribe(res => console.log(res));

Alternatively, you can use:

this.form.valueChanges.subscribe(res => console.log(res));

You can also enhance this functionality by incorporating validation or other features:

import { filter, map, startWith  } from 'rxjs/internal/operators';
....
   this.form.valueChanges
    .pipe(
      filter(() => this.form.valid),
      map(data => {
        // Append last update time to result
        data.lastTime = new Date();
        return data;
      })
    )
    .subscribe(res => console.log(res));

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

Which rxjs operator functions similarly to concatmap, but delays the firing of the next request until the current one is completed?

Imagine if I need to make multiple api calls with a high risk of encountering race conditions. If I send 3 requests simultaneously to update the same data on the server, some of the information could be lost. In order to prevent this data loss, I want to ...

Error: React - Unable to access the 'lazy' property because it is undefined

I used a helpful guide on the webpack website to incorporate TypeScript into my existing React App. However, upon launching the app, an error message pops up saying: TypeError: Cannot read property 'lazy' of undefined The version of React being ...

What is the process for converting/executing TypeScript into JavaScript?

Having trouble running https://github.com/airgram/airgram Encountering this warning message from the post (node:9374) Warning: To load an ES module, set "type": "module" Have already added {"type": "module"} To pa ...

Encountering a compilation error due to a Typescript assignment

While working with Typescript, I encountered a compilation error in the code shown below: console.log('YHISTORY:login: data = '+data); let theData = JSON.parse(data); console.log('YHISTORY:login: theData = '+JSON.stringify(theData)); ...

Issues with Webpack bootstrap-loader: Unable to locate './bootstrap-styles' and Unable to locate './bootstrap-scripts'

I am attempting to integrate bootstrap-loader into my angular 2 project. However, during Webpack compilation, I am encountering errors: ERROR in ./~/bootstrap-webpack/index.js Module not found: Error: Can't resolve './bootstrap-styles' in & ...

Challenges with implementing ng2-auto-complete in Angular2

I successfully integrated the Angular 2 ng2-auto-complete component into my project by following this helpful tutorial. The code is also available on GitHub. The current challenge I am encountering involves the formatting of my data source. It is structur ...

Angular library modules for node packages

After developing my latest library, I noticed some red underlines: https://i.stack.imgur.com/ffAjI.png In this package, I plan to incorporate other npm packages like ionic and crypto. I attempted to update the package.json within the library: { "name ...

Util Deprecations resolved with TSLint Autofix

Is there a feature in VSCode that can automatically fix deprecations related to the util library? For example: if (isNullOrUndefined(this.api)) { Would be better written as: if (this.api === null || this.api === undefined) { While there isn't an ...

Steps to add annotations to a class descriptor:

Can you help me with the correct way to annotate this piece of code? export class TestCls { static SomeStaticFn(): TestCls { // Do some stuff... // Return the class descriptor for a "fluid usage" of SomeStaticFn return TestCls ...

Retrieving an image from a JSON file based on its corresponding URL

I am trying to extract the URL and display it as an image: This is how it appears in JSON: https://i.sstatic.net/vpxPK.png This is my HTML code: <ul> <li *ngFor="let product of store.Products"> <p>Product Image: {{ product.Pr ...

Fixing the Bootstrap Datepicker: A Step-by-Step Guide

Is there a way to configure the Datepicker to display today's date and tomorrow's date? Click here for the JS file Check out the image on our website https://i.stack.imgur.com/VyFUB.jpg ...

Adding a Unique Variant to Material-UI Component in React/ Typescript

I am currently working on creating a customized component inspired by Material-ui components but with unique styles added. For instance, the Tab component offers variants such as ["standard","scrollable","fullWidth"], and I want to include 'outline ...

Issues with maintaining the checked state of radio buttons in an Angular 4 application with Bootstrap 4

In my Angular 4 reactive form, I am struggling with the following code: <div class="btn-group" data-toggle="buttons"> <label class="btn btn-primary" *ngFor="let item of list;let i=index" > <input type="radio" name="som ...

Show images from an array of base64 image data

I am currently facing an issue while trying to display images in base64 format within a RadListView component. Within the loop of the component, I have the following code snippet: let base64ImageSource = new ImageSource; base64ImageSource = fromBase64(re ...

When I try to refresh the URL in Angular, I keep getting a 404 error

I recently uploaded my Angular application on a server. Upon clicking the server URL, I am immediately redirected to the login page. However, if I try to refresh the same URL with "/login" suffix, I encounter a 404 not found error message. The original URL ...

Transform JSON into a TypeScript interface with a specialized Date method

Within my Angular 7 project, there is a Post Model defined as follows: export interface PostModel { id: number; created: Date; published: boolean; title: string; } I have implemented an Angular service method aimed at retrieving posts: public g ...

What are the best techniques for concentrating on a kendo maskedtextbox?

What is the correct way to set focus on the kendo-maskedtextbox in TypeScript after the view has initialized? The information provided in Telerik's example here is lacking in detail. ...

What is the process for integrating GraphQL resolvers in Typescript using Graphql-codegen?

With the goal of learning Apollo Server, I decided to implement the schema outlined here. The CodeGen produced what seemed to be logical type definitions for books and libraries. export type Book = { __typename?: 'Book'; author: Author; tit ...

OnDrop event in React is failing to trigger

In my current React + TypeScript project, I am encountering an issue with the onDrop event not working properly. Both onDragEnter and onDragOver functions are functioning as expected. Below is a snippet of the code that I am using: import * as React from ...

Risky assignment of an 'any' value" encountered while implementing react-transition-group in TypeScript

Encountering @typescript-eslint errors while implementing the Transition component from react-transition-group. Implemented the official React Transition Group example for JS in a TypeScript + ESLint project, resulting in the error message: Unsafe assignm ...