I am looking to retrieve a Datepicker value from a Child Component and utilize it within an onClick event in the Parent component

One of the challenges I am facing is integrating two separate DatePickers in my Angular project to create a date range search functionality for my local database. I have set up an API to connect to the database and implemented forms to retrieve data. To tackle this issue, I created a child component with a DatePicker and then used it twice within the parent Component form. Here's a snippet of the Child Component:

date-range.component.html

<div class="input-group">
  <input  class="form-control mb-2 mr-sm-2" [name]="name" 
         placeholder="From date" value="" [(ngModel)]="model" 
         #dp="ngbDatepicker" ngbDatepicker>
  <div class="input-group-append">
    <button class="btn btn-outline-secondary calendar mb-2 mr-sm-2" (click)="dp.toggle()"></button>
  </div>
</div>

date-range.component.ts

@Component({
  selector: 'app-date-range',
  templateUrl: './date-range.component.html',
  styleUrls: ['./date-range.component.css']
})
export class DateRangeComponent {

  @Input() model: Date;
  @Output() dateModel = new EventEmitter<Date>();
  

  constructor() { }

  onChange() {
    this.dateModel.emit(this.model);
  }

  }

The Parent Component references the Child Component like so:

product-list.component.html

<app-date-range name="dp1" (dateModel)="dateModel($event)" [model]="model"
                    #productFromDate>

</app-date-range>
<app-date-range name="dp2" (dateModel)="dateModel($event)" [model]="model"
                    #productToDate>

    </app-date-range>
    
    <button (click)=
"searchProducts(productFromDate.value, productToDate.value);" type="submit" class="btn btn-primary">Search</button>

And the TypeScript code looks like this:

product-list.component.ts

 export class ProductListComponent implements OnInit {
    
    model: Date = null;
    
constructor(private productService: ProductService) { }

  ngOnInit(): void {
    // default search on page load
    this.searchProducts('', '', '', '10');
  }
    dateModel(date: Date) {
        this.model = date;
      }
    
    }

I have been struggling to pass the date values from the Child DatePickers to use them in my search method such as productFromDate.value. Any guidance or tips would be greatly appreciated as I am still relatively new to Angular, having worked with it for only three weeks.

Update:

I revamped the entire process using Angular Material Date-Picker and successfully utilized MatDatepickerInputEvent to achieve the desired functionality.

Answer №1

One issue that stands out is the lack of implementation of OnChanges within your DateRangeComponent class.

export class Date RangeComponent implements OnChanges

Furthermore, it's important to add the ngOnChanges function:

ngOnChanges(changes: SimpleChanges) {
    // insert your code here
}

To observe the changing values, consider using console.log to keep track of any updates.

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 process for creating a default button in Ionic framework?

Recently, I developed an app that includes a survey page. Each question in the survey has two buttons for the user to select: Yes or No. However, as a newcomer to using Ionic, I encountered an issue after building the code and checking the output. One of ...

Are there any comparable features in Angular 8 to Angular 1's $filter('orderBy') function?

Just starting out with Angular and curious about the alternative for $filter('orderBy') that is used in an AngularJS controller. AngularJS example: $scope.itemsSorted = $filter('orderBy')($scope.newFilteredData, 'page_index&apos ...

Honing into Angular 2 Events

I am struggling with something that should be simple, but I can't seem to make it work. My goal is to utilize screenfull, which is included in a theme I'm using, to enable fullscreen mode on the browser. Specifically, I want to execute certain ac ...

Tips for adjusting the color of the snackbar in Angular

When a user logs out, I am using snackBar to display a message. I want to change the color of the panel from dark grey to another color and tried using the following solution: panelClass: ['danger'] supposed to change the panel color to red ( ...

Creating a Fixed-length Array in TypeScript

Seeking assistance with TypeScript types, I have a particular question. When declaring a type for an array as follows... position: Array<number>; ...it allows for creating an array of any length. However, if you need an array containing numbers of ...

Using an object as an array index in Javascript

I have been utilizing a crossword application from this specific repository: https://github.com/jweisbeck/Crossword . The issue I am facing is that the program is using jquery version 1.6.2 while my entire project is built on jquery-3.1.1 version. The erro ...

Tips for preventing CORS and SSL issues when using localhost

Attempting to log in with Google on my Svelte app involves sending a request to an Express server. However, I encounter different errors on different browsers. On Firefox, I receive a Cross-Origin Request Blocked: The Same Origin Policy disallows reading t ...

TypeScript: a sequence of symbols representing a particular <type>

Perhaps I'm going crazy. I have a roster of potential nucleotides and a corresponding type: const DNA = ['G', 'C', 'T', 'A'] as const; type DNA = typeof DNA[number]; So, a DNA strand could be a sequence of an ...

Ways to change information in a class variable using Angular

A sample registration application has been created and I am looking to store the data in a class data model. Below is the class model that has been created: export class Model { name: string; tableData: any[]; constructor() { this.tableData = [ ...

What could be causing my "Swiper" component to malfunction in a TypeScript React project?

In my React project, I decided to incorporate the Swiper library. With multiple movie elements that I want to swipe through, I began by importing it as follows: import Swiper from 'react-id-swiper'; Utilizing it in my code like this: <div cla ...

I'm trying to determine in Stencil JS if a button has been clicked in a separate component within a different class. Can anyone assist

I've created a component named button.tsx, which contains a function that performs specific tasks when the button is clicked. The function this.saveSearch triggers the saveSearch() function. button.tsx {((this.test1) || this.selectedExistingId) && ...

Build encountered an error: module exported a null value unexpectedly

Encountering an error message while running the Angular Build (ng build --prod): ERROR in: Unexpected value 'null' exported by the module 'SharedModule' @NgModule({ declarations: [InputComponent, InputSimpleComponent, ModelEditComp ...

Combining Vue with Typescript and rollup for a powerful development stack

Currently, I am in the process of bundling a Vue component library using TypeScript and vue-property-decorator. The library consists of multiple Vue components and a plugin class imported from a separate file: import FormularioForm from '@/FormularioF ...

Creating multiple objects with key-value pairs from JSON properties in TypeScript and React

I'm struggling to incorporate fetched data from an API into a Recharts line chart. The issue lies in mapping the JSON data properly. The API returns data that represents the count of predictions for each month, with a 0 value for months where no predi ...

Combining an external class with a namespace in TypeScript

Valid Script Code: class InputField { } namespace InputField { export enum Types { text = "text", number = "number" } } export { InputField }; Invalid Script Code: import InputField from "@Controls/InputFields/Inp ...

Encountered the issue of No suitable overload found for this call in React with Typescript

While working on a React project, I encountered an issue with my form component's onSubmit event showing an error message "No overload matches this call". The code snippet causing the problem is as follows: <StyledForm onSubmit={this.handleSave}&g ...

In my array, I have numerous objects that need to be inserted into a PostgreSQL database using a single query executed from a Node.js environment

After receiving the data from the frontend, all the information is stored in req.body. The next step involves mapping the data and attempting to insert it, however, an error is being encountered. router.post('/addItems', (req, res) => { ...

Angular ng-select displaying the "&" symbol as "&amp;"

I am encountering a situation where the selected option is displaying with "&" instead of just "&" character. Is there a way to display the string value as is without interpreting it as HTML code, while also ensuring there are no security vulnerabilit ...

Developing an attribute in a constructor using Typescript

My javascript code is functioning perfectly: class myController { constructor () { this.language = 'english' } } However, I encountered an issue when trying to replicate the same in Typescript export default class myController { co ...

Error message MSB6006 in Visual Studio Code: The "CL.exe" process terminated with exit code -1073741515

I am currently developing an Angular 4 project using Visual Studio Code IDE. I would like to integrate a modal dialog into my project, but I encountered an error message when attempting to run the 'npm install --save ng2-modal-dialog' command in ...