Is there an alternative method to retrieve model value on controller in Angular bootstrap ngbdatepicker since the (change) method has been removed?

Currently, I am working with ngbdatepicker in Bootstrap. I have added a datepicker selector to appcomponent.html and the datepicker is showing up. Now, I need to retrieve that model value into the controller so that I can pass it to the parent appcomponent. To achieve this, I added a (change) method to the datepicker, but it seems to be removing that method from the input. Can anyone suggest another way for me to read and pass that value to the parent component?

Thank you in advance.

In the template below, I am using the child selector to open the datepicker. I have added a change method, but it's not triggering on the date selection, so I'm unable to emit the event.

Parent Component:

<ng-template #modalContent let-close="close" *ngIf="true">
  <div class="modal-header">
    <h5 class="modal-title">Add new event</h5>
    <button type="button" class="close" (click)="close()">
      <span aria-hidden="true">×</span>
    </button>
  </div>
  <div class="modal-body">
  <label>Start Date</label><date-pick (change)="updateFromChild($event)"></date-pick>
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-outline-secondary" (click)="close()">OK</button>
  </div>
</ng-template>

Child Component:

import {Component, Input, Output, EventEmitter} from '@angular/core'

@Component({
  selector: 'date-pick',
  templateUrl: './datepicker-popup.html'
})
export class NgbdDatepickerPopup {
  model;
  constructor(){  }
  @Output() change: EventEmitter<any> = new EventEmitter<any>();
  onChange() {
      console.log('call');
      this.change.emit(this.model)
  }
}
Child Template:

<form class="form-inline">
  <div class="form-group">
    <div class="input-group">
      <input class="form-control" placeholder="yyyy-mm-dd"
             name="dp" [(ngModel)]="model" ngbDatepicker #d="ngbDatepicker" (change)="onChange()">
      <div class="input-group-append">
        <button class="btn btn-outline-secondary" (click)="d.toggle()" type="button">
          <img src="img/calendar-icon.svg" style="width: 1.2rem; height: 1rem; cursor: pointer;"/>
        </button>
      </div>
    </div>
  </div>
</form>

https://i.sstatic.net/W9aGg.png

Answer №1

After taking your input into consideration, I made the following changes and it is now working properly.

Installed:

npm install --save @ng-bootstrap/ng-bootstrap

app.component.html

<app-date-picker (selectDate)="change($event)" ></app-date-picker>

app.component.ts

change(event) {
    alert(event);
    console.log(event);
  }

datepicker.component.html

<form class="form-inline">
  <div class="form-group">
    <div class="input-group">
      <input class="form-control" placeholder="yyyy-mm-dd"
             name="dp" [(ngModel)]="model" (ngModelChange) = "change($event)" ngbDatepicker #d="ngbDatepicker">
      <div class="input-group-append">
        <button class="btn btn-outline-secondary" (click)="d.toggle()" type="button">
          <img src="img/calendar-icon.svg" style="width: 1.2rem; height: 1rem; cursor: pointer;"/>
        </button>
      </div>
    </div>
  </div>
</form>

datepicker.component.ts

@Component({
  selector: 'app-date-picker',
  templateUrl: './datepicker.component.html',
})
export class DatePickerComponent {
  model;
  @Output() selectDate = new EventEmitter<any>();

  change(event) {
    this.selectDate.emit(event);
  }
}

Instead of using (change)="onChange()", make use of

(ngModelChange)="onChange($event)"

 onChange(event) {
      console.log('call');
      this.change.emit(event);
  }

In Angular, you can do binding with [(ngModel)]='property' to enable two-way binding to the control.

If you have a parent-child component scenario, you need to use EventEmitter to publish values to the parent component. Here's how you can do it:

 // In child component
 @Output() selectDate = new EventEmitter<string>();
 // On date change, emit the date 
 this.selectDate.emit(value);

In the parent component, it should be like this:

   <childComponent (selectDate)='OnSelectDate($event)'></childComponent>
   // In the TypeScript file, you need to have the method 
   OnSelectDate(event) {}

Answer №2

If you find yourself here and believe that your code is identical but not functioning, remember that the sequence of ngModel and ngModelChange is crucial! NgModelChange must always come after ngModel for the code to work as expected. Take a look at https://github.com/angular/angular/issues/11234 for more information.

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

Automate your Excel tasks with Office Scripts: Calculate the total of values in a column depending on the criteria in another column

As a newcomer to TypeScript, I have set a goal for today - to calculate the total sum of cell values in one column of an Excel file based on values from another column. In my Excel spreadsheet, the calendar weeks are listed in column U and their correspon ...

Is there a way to enable intellisense in vscode while editing custom CSS within a material-ui component?

Is there a vscode extension recommendation for intellisense to suggest css-in-js for customized material ui components in .tsx files? For example, I want intellisense to suggest 'backgroundColor' when typing. The closest I found is the 'CSS- ...

Issue encountered while attempting to compare '[object Object]'. This operation is restricted to arrays and iterables

I'm puzzled by this error that keeps popping up in my code. The issue seems to be occurring in AppComponent.html:4. An error is appearing related to '[object Object]'. It seems that only arrays and iterables are allowed. app.component.ht ...

What is the process for defining a default value for a template-driven form input in Angular 2?

I have a simple input element in my form that requires a default initial value to be set. <input type="number" name="interest_rate" [(ngModel)]="interest_rate"> In my code, I included this.form.controls['interest_rate'].patchValue(this.a ...

How to Restrict the Number of Rows Displayed in an Angular 4 Table

Currently, I am faced with a situation where I have a lengthy list of entries that I need to loop through and add a row to a table for each entry. With about 2000 entries, the rendering process is slowing down considerably. Is there a way to limit the disp ...

The issue arises when TypeScript is unable to accurately infer the type as not being undefined following a type guard condition using

The following code snippet illustrates that in the else statement, it is evident that b cannot be undefined (a||b returns truthy and since a is falsy, b must be truthy). Why does Typescript show the error 'b' is possibly 'undefined', a ...

Developing step code for CucumberJS Scenario Outlines

In my feature file, I have the following scenario outlined for testing colors: Feature: Color feature @test Scenario Outline: Test color Given the first color is <COLOR_ONE> And the second color is <COLOR_TWO> ...

Can Ansible and Pulumi be integrated to work together effectively?

Is it possible to create multiple DigitalOcean droplets in a loop and then use Ansible to configure software and security measures on them, similar to how Terraform works? If so, what would the JavaScript/TypeScript code for this look like? I couldn' ...

Tips on expanding typings in TypeScript?

In my software library, there exists a map function with the following definitions: function map<T, U>(f: (x: T) => U, a: Array<T>): Array<U> function map<T, U>(f: (x: T) => U, a: Functor<T>): Functor<U> Furtherm ...

Tips on ending an interval in rxjs once it has started

Implemented a code in an Angular component to retrieve data from a service every 10 seconds on initialization. Now, I need to find a way to stop the interval after a certain period of time such as 5 minutes or when all the necessary data has been collected ...

Displaying a limited number of dynamically generated values in an Angular select dropdown using Bootstrap 5

I have a backend service that provides a list of all countries. In my component, I iterate through the array and allow the user to select a country. Bootstrap 5 is being used for styling. <select class="form-select" formControlName="coun ...

When choosing the child option, it starts acting abnormally if the parent option is already selected in Angular

I am encountering an issue while trying to select the parent and its children in the select option. The concept is to have one select option for the parent and another for the child. I have parent objects and nested objects as children, which are subCatego ...

Having trouble fixing TypeScript bugs in Visual Studio Code

I am encountering a similar issue as discussed in this solution: Unable to debug Typescript in VSCode Regrettably, the suggested solution does not seem to resolve my problem. Any assistance would be greatly appreciated. My directory structure looks like ...

Creating click event handler functions using TypeScript

I encountered an issue when trying to set up an event listener for clicks. The error message I received was that classList does not exist on type EventTarget. class UIModal extends React.Component<Props> { handleClick = (e: Event) => { ...

What is preventing me from connecting to dockerized npm from my host machine?

Issue - A server running inside a docker container is not responding when accessed from outside the container on an OSX host. web: image: my_web build: context: ./ dockerfile: web.docker container_name: my_web networks: ...

The property xyz is not found in the type 'IntrinsicAttributes & interface abc'

I have an array of objects structured like this: const data = { "Large_Plates": [ { "name": "Cauliower/ Shanghai Fried rice with stir fry vegetables", "id": "1", "price_Veg&quo ...

Angular threw an error saying: "Template parse errors: is not a recognized element"

I am attempting to utilize babel standalone within a react application to transpile Angular TypeScript. The transpiling process seems to be successful, however, I encounter an error when trying to import a component and use its selector within the template ...

Attempting to run the command "npx typescript --init" resulted in an error message stating "npm ERR! could not determine executable to run."

What could be the reason behind the error message npm ERR! could not determine executable to run? Currently, I am attempting to set up a basic Node.js application using TypeScript and Yarn. Yarn is a tool that I am not very familiar with. These are the c ...

Utilizing Angular 8's Reactive Form to Transform Checkbox Event Output into a String Format

My form is reactive and includes a field called Status, which can have the values 'A' or 'I': this.form = this.formBuilder.group({ result_info: this.formBuilder.array([ this.getResultcontrols()]), stat ...

Angular HTTP Patch method requires explicitly defined HTTP options as input parameters

I encountered a challenge with using Angular's HTTP patch method and noticed that the overloaded function patch(url, body, options) only accepts hardcoded values for HTTP options. An example of a hardcoded approach that works: patchEntity(id: number) ...