The DatePicker in Angular2 and Typescript is unable to execute the property 'toggle' because it is undefined

I've encountered an issue with the calendar icon for angular2's datepicker. Whenever I try to click on it, I keep getting this error:

TypeError: Cannot read property 'toggle' of undefined at Object.eval [as handleEvent] (AdmissionDialogComponent.html:1) at handleEvent (core.es5.js?de3d:11997) at callWithDebugContext (core.es5.js?de3d:13458) at Object.debugHandleEvent [as handleEvent] (core.es5.js?de3d:13046) at dispatchEvent (core.es5.js?de3d:8601) at eval (core.es5.js?de3d:9212) at HTMLButtonElement.eval (platform-browser.es5.js?41b7:2651) at ZoneDelegate.invokeTask (zone.js?6524:424) at Object.onInvokeTask (core.es5.js?de3d:3881) at ZoneDelegate.invokeTask (zone.js?6524:423)

Below are the codes I am using for setting up the start date and end date that are causing the issue:

<div class="col-sm-2">

    <div class="input-group">
        <input id="field_treatmentStartDate" type="text" class="form-control" name="treatmentStartDate" ngbDatepicker #tStartDateDp="ngbDatepicker"
            *ngIf="admission.treatment" [(ngModel)]="admission.treatment.startDate" />
        <span class="input-group-btn">
            <button type="button" class="btn btn-default" (click)="tStartDateDp.toggle()"><i class="fa fa-calendar"></i></button>
        </span>
    </div>
    <div [hidden]="!(editForm.controls.treatmentStartDate?.dirty && editForm.controls.treatmentStartDate?.invalid)">
        <small class="form-text text-danger" [hidden]="!editForm.controls.treatmentStartDate?.errors?.ZonedDateTimelocal" jhiTranslate="entity.validation.ZonedDateTimelocal">
                                        This field should be a date and time.
                                    </small>
    </div>

    <div [hidden]="!treatmentStartDateIsNull">
        <small class="form-text text-danger">
                                        Missing treatment start date.
                                    </small>
    </div>

</div>
<!-- start date -->

...

...

In the component.ts file, I have initialized empty values for the admission model in the "ngOnInit" function.

this.admission.patient = this.patient;
this.admission.bed = this.bed;
this.admission.bed.ward = this.ward;
this.admission.treatment = this.treatment;

Despite setting up blank attributes in the admission value, I'm confused as to why some parts are working while others are not. I have declared attributes like below in the ngOnInit function:

treatment: Treatment = new Treatment();

Answer №1

Shift the *ngIf statement up to the parent div:

<div class="input-group" *ngIf="admission.treatment">...

Then remove it from the <input>

Alternatively, you can utilize [hidden].

Since *ngIf eliminates the <input> element from the DOM when the condition is false and even when the condition is true, it can lead to errors if a reference to a local template variable is not created. Avoid using template variables and *ngIf together.

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

An issue occurred while attempting to retrieve information from the database table

'// Encounter: Unable to retrieve data from the table. // My Code const sql = require('mssql/msnodesqlv8'); const poolPromise = new sql.ConnectionPool({ driver: 'msnodesqlv8', server: "test.database.windows.net", ...

Tips for creating a unique custom rounded underline effect in an Angular Material Tab

Our design team has requested that we incorporate underlines that resemble the top half of a rectangle with rounded corners. We are currently using Angular Material, but I am facing difficulties in styling the existing tabs component (https://material.angu ...

Why is my React component not being updated with Routes?

I'm new to using react-router and I'm struggling with it for the first time. Here is the code snippet: App.tsx import React from 'react'; logo = require('./logo.svg'); const { BrowserRouter as Router, Link, Route } = require ...

Tips for preventing the exposure of internal components in Angular

Imagine an OutlookBarComponent that contains various bars similar to those seen in Microsoft Outlook. Each bar has a child component called OutlookBarItemComponent. Both the OutlookBarComponent and OutlookBarItemComponent are encapsulated within the Contro ...

Using ngClass for conditional styling in Angular 7: A step-by-step guide

Utilizing multiple classes within Angular's [ngClass] functionality is my current challenge. The goal is to make it function based on the flag condition provided by the component.ts file. ...

When running the ng test command, the error "TypeError: The 'compilation' argument must be an instance of Compilation" is generated, but the ng build command functions correctly

When attempting to execute unit tests using 'ng test libraryprojectname', I encounter the following error. Interestingly, ng build functions properly without any issues. The project in question is a workspace that includes an Angular library. Any ...

Setting a cookie within an Angular interceptor

My angular interceptor function includes a request object. intercept(req: HttpRequest<any>, next: HttpHandler) { return next.handle(req); } I am looking to set my token in the request cookie under the name my-token. How can I achieve this? I ...

Is it possible to continuously activate an Angular Input setter using a Subject?

Is there a way to activate an @Input setter without providing a value, by utilizing RxJS' Subject()? It seems that the setter only gets triggered once, most likely because no value has been changed. How can I ensure that the input is activated every ...

Ways to resolve the error message "TypeError: 'setOption' is not a function on type 'MutableRefObject' in React"

CODE export default function EChart({ option, config, resize }) { let chart = useRef(null) let [chartEl, setChartEl] = useState(chart) useEffect(() => { if (resize) { chartEl.resize() } if (!chartEl.cu ...

When selecting the "Open Link in New Tab" option in Chrome, the Angular app's routing will automatically redirect to the login page

I am facing a peculiar issue in my Angular 2 application that I need help troubleshooting. Currently, the routing within my app functions as intended when I click on links to navigate between different components. Here is an example of how the routing path ...

minimize the size of the image within a popup window

I encountered an issue with the react-popup component I am using. When I add an image to the popup, it stretches to full width and length. How can I resize the image? export default () => ( <Popup trigger={<Button className="button" ...

The Angular material table is having compilation issues due to an unexpected closing tag for "ng-container"

Currently, I am in the process of working on an Angular project that involves integrating Angular Material version 5.2.5. Below is a snippet from my app.component.ts: import { Component } from '@angular/core'; import {MatTableDataSource} from & ...

Issue with ngNonBindable directive not functioning properly in Angular 2

One of the challenges I am facing is displaying source code using Google Pretty Print within my app component. I attempted to use ngNonBindable within the 'pre' tag, but encountered an error during compilation/runtime. zone.js:388Unhandled Promi ...

What is the best approach to incorporate Column Reordering in react-data-grid?

Within my REACT application, I have incorporated the npm package react-data-grid. They offer a sample showcasing Column Reordering on their website. I wish to replicate this functionality in my own code. Upon reviewing their source code, I am puzzled abou ...

"Encountered a 'Module not found: Error: Can't resolve' issue while attempting to install from GitHub. However, the standard installation process

I am currently utilizing the Quilljs JavaScript library for a project in Angular. After installing it with the following command: npm install --save quill Everything appears to be functioning correctly, and I am able to import the Quill class into my Ty ...

Encountering difficulties in transmitting ngModel across multiple layers

I'm encountering a problem when trying to pass ngModel through the second child component. It seems that as soon as I do that, it stops working. In order to pass the ngModel, I implemented this abstract class: export abstract class AbstractValueAcces ...

Can I specify which modal or component will appear when I click on a component?

Working on a small Angular 5 project, I have a simple component that represents a food product shown below: [![enter image description here][1]][1] This component is nested within my main component. When this component is clicked, a quantity component/m ...

ng serve in Angular 6 may cause compatibility issues with HttpClientModule and mat-icons

After implementing basic unit tests with Jest, I encountered an issue where my mat-icons were not displaying correctly and my HttpClient calls to the backend were returning empty responses when running the Angular app with "ng serve." Despite subscribing t ...

Error: TypeScript Knockout table failing to display data

I have a table that displays invoices, along with a nested table showing the individual checks associated with each invoice. I am using knockout and typescript to render these tables. Currently, I can successfully display the invoices but am facing difficu ...

app-root component is not populating properly

As a newcomer to Angular 2, I have embarked on a small project with the following files: app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { MaterialModule } fro ...