What could be the reason for the following error message: "ERROR TypeError: Unable to access 'controls' property of an undefined object"?

Currently, I am attempting to follow a tutorial from Pluralsight but have encountered an issue that has left me stumped. Strangely enough, the application is functioning correctly; however, I keep seeing an error pop up in my console.

I've taken it upon myself to investigate and identify the root of this problem, but despite my efforts, I suspect that my lack of experience might be hindering me from finding a solution.

The issue appears to revolve around the code snippet below: create-event.component.html

<h1>New Event</h1>
<hr>
<div class="col-md-6">
  <form #newEventForm="ngForm" (ngSubmit)="saveEvent(newEventForm.value)" autocomplete="off" novalidate>
    <div class="form-group" [ngClass]="{'error': newEventForm.controls.name?.invalid && newEventForm.controls.name?.touched}">
      <label for="eventName">Event Name:</label>
      <em *ngIf="newEventForm.controls.name?.invalid && (newEventForm.controls.name?.touched)">Required</em>
      <input (ngModel)="newEvent.name" name="name" required id="name" type="text" class="form-control" placeholder="Name of your event..." />
    </div>
    <div class="form-group" [ngClass]="{'error': newEventForm.controls.date?.invalid && newEventForm.controls.date?.touched}">
      <label for="eventDate">Event Date:</label>
      <em *ngIf="newEventForm.controls.date?.invalid && (newEventForm.controls.date?.touched)">Required</em>
      <input (ngModel)="newEvent.date" name="date" required id="eventDate" type="text" class="form-control" placeholder="format (mm/dd/yyyy)..." />
    </div>
    <div class="form-group" [ngClass]="{'error': newEventForm.controls.time?.invalid && newEventForm.controls.time?.touched}">
      <label for="eventTime">Event Time:</label>
      <em *ngIf="newEventForm.controls.time?.invalid && (newEventForm.controls.time?.touched)">Required</em>
      <input (ngModel)="newEvent.time" name="time" required id="eventTime" type="text" class="form-control" placeholder="start and end time..." />
    </div>
    <div class="form-group" [ngClass]="{'error': newEventForm.controls.price?.invalid && newEventForm.controls.price?.touched}">
      <label for="eventPrice">Event Price:</label>
      <em *ngIf="newEventForm.controls.price?.invalid && (newEventForm.controls.price?.touched)">Required</em>
      <input (ngModel)="newEvent.price" name="price" required id="eventPrice" type="text" type="number" class="form-control" placeholder="event price..." />
    </div>

    <div ngModelGroup="location">
      <div class="form-group">
        <label for="address">Event Location:</label>
        <input (ngModel)="newEvent.address" name="address" id="address" type="text" class="form-control" placeholder="Address of event..." />
      </div>
      <div class="row">
        <div class="col-md-6">
          <input (ngModel)="newEvent.city" name="city" id="city" type="text" class="form-control" placeholder="City..." />
        </div>
        <div class="col-md-6" >
          <input (ngModel)="newEvent.country" name="country" id="country" type="text" class="form-control" placeholder="Country..." />
        </div>
      </div>
    </div>

    <div class="form-group">
      <label for="onlineUrl">Online Url:</label>
      <input (ngModel)="newEvent.onlineUrl" name="onlineUrl" id="onlineUrl" type="text" class="form-control" placeholder="Online Url..." />
    </div>
    <div class="form-group" [ngClass]="{'error': newEventForm.controls.imageUrl?.invalid && newEventForm.controls.imageUrl?.touched}">
      <label for="imageUrl">Image:</label>
      <em *ngIf="newEventForm.controls.imageUrl?.invalid && newEventForm.controls.imageUrl?.touched && newEventForm.controls.imageUrl?.errors.required">Required</em>
      <em *ngIf="newEventForm.controls.imageUrl?.invalid && newEventForm.controls.imageUrl?.touched  && newEventForm.controls.imageUrl?.errors.pattern">Must be a png or jpg url</em>
      <input (ngModel)="imageUrl" name="imageUrl" required pattern=".*\/.*.(png|jpg)" id="imageUrl" type="text" class="form-control" placeholder="url of image..." />
      <img [src]="newEventForm.controls.imageUrl.value" *ngIf="newEvent.controls.imageUrl?.valid" />
    </div>

    <button type="submit" class="btn btn-primary">Save</button>
    <button type="button" [disabled]="newEventForm.invalid" class="btn btn-default" (click)="cancel()">Cancel</button>
  </form>
</div>

create-event.component.ts

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { EventService } from './shared';

@Component({
  templateUrl: 'create-event.component.html',
  styles: [`
  em {float: right; color: #E05C65; padding-left: 10px;}
  .error input {background-color: #E3C3C5;}
  .error ::-webkit-input-placeholder {color: #999;}
  .error ::-moz-placeholder {color: #999;}
  .error :-moz-placeholder {color: #999;}
  .error :ms-input-placeholder {color: #999;}
  `]
})

export class CreateEventComponent {
  newEvent;
  isDirty = true;

  constructor(private router: Router,
              private eventService: EventService) {}

  saveEvent(formValues) {
    this.eventService.saveEvent(formValues);
    this.isDirty = false;
    this.router.navigate(['events']);
  }

  cancel() {
    this.router.navigate(['events']);
  }
}

An error message keeps popping up pointing to line 49 of the html file, specifically:

<input (ngModel)="imageUrl" name="imageUrl" required pattern=".*\/.*.(png|jpg)" id="imageUrl" type="text" class="form-control" placeholder="url of image..." />

The error being displayed reads: "ERROR TypeError: Cannot read property 'controls' of undefined". Can someone shed light on what could be causing this error?

Answer №1

The issue lies within the line below:

  <img [src]="newEventForm.controls.imageUrl.value" *ngIf="newEvent.controls.imageUrl?.valid" />

The correct syntax should be

*ngIf="newEventForm.controls.imageUrl?.valid"

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

The `createAction` function does not preserve the data type when used with `ofType`

I'm currently developing a mobile application that allows users to choose snacks from a list of available options retrieved from an external API. To handle actions and dispatch API requests, I am utilizing redux-observable. Below is my existing code, ...

Issues with responsiveness and calculated attributes in Vue 3 using the Composition API

Within this menu, there are different items: Item 1 (marked as number 1 in orange) with the path: http://localhost:8080/#/documents Item 2 (marked as number 2 in orange) with the path: http://localhost:8080/#/documents/1 Item 3 (marked as number 3 in or ...

Generating divs dynamically with inline styling and utilizing ngFor, while incorporating a conditional check with ngIf in Angular

Currently, I have an Angular component where I am dynamically generating div elements using the ngFor directive. However, I also need to validate a condition before creating each div, and I'm facing challenges when trying to use both ngFor and ngIf in ...

Encountered an issue trying to access undefined properties while reading 'PP'

I am trying to showcase the data retrieved from my JSON file. Here is a glimpse of the information stored in the JSON => Within DTA > PP , I am specifically interested in displaying the variable NOMFAMILLE. An error message has caught my attentio ...

I encountered an issue while trying to install the Angular and npm package

After updating Nodejs, I decided to delete the old version of Angular and install a new one. However, I encountered an error during the installation process. https://i.sstatic.net/M5VOc.png I followed a series of steps in an attempt to resolve the issue, ...

Initial values are not retained for nested form components upon submission

In an attempt to incorporate nested form components in Angular using reactive forms and ControlValueAccessors, I have been following a helpful guide available at the following link: While most of my implementation is working correctly, I am encountering o ...

Add the specified HTML tag to the existing document. An error has occurred: HierarchyRequestError - The action would result in an invalid node

During my testing of a React/TypeScript project using Jest + Enzyme, I encountered an issue when trying to append an HTML tag. The error occurred with the following unit test code: const htmlTag: HTMLElement = document.createElement('html'); htm ...

Sharing data between two Angular 2 component TypeScript files

I'm facing a scenario where I have two components that are not directly related as parent and child, but I need to transfer a value from component A to component B. For example: In src/abc/cde/uij/componentA.ts, there is a variable CustomerId = "sss ...

Communicating between Angular and Node (MEAN) involves transmitting basic user information, such as email address and user ID, from Node

I've encountered an issue with the following code snippet: // Node.js router.get('/users/all', authenticate, (req, res) => { User.find({some query}).select('firstName lastName email').then((users) => { res.send(u ...

What is the process for importing a CSV or TXT file into a platform?

I have a new project that involves working with a large dataset of dummy information. The data is stored in a csv file located in the assets folder, and it consists of over 200 lines. My task is to read the file without needing to make any changes to it. ...

The specified path "/src/app/app.module.ts" was not found while attempting to add ng in an Angular project that is using a custom path

I encountered an issue while attempting to integrate Angular Universal into my project. Here is my folder structure: src main app app.module.ts node_modules tsconfig.json My project uses Angular version 15.2.5 and the latest version of Angular Uni ...

What steps can be taken to ensure that VS Code correctly identifies TypeScript declarations within mono-repo packages?

I'm currently working on a mono-repo project setup with an isolated library package in TypeScript and another web UI package that combines TypeScript and React. To import the compiled library package into the consumer (web UI) package, I'm using ...

Accessing dynamically inserted child components in Angular 2.0

Currently, I am utilizing this sample to dynamically generate components within my application. export class App { @ViewChild('placeholder', {read: ViewContainerRef}) viewContainerRef; private componentFactory: ComponentFactory<any> ...

Tips for resolving this unhandled error in React TypeScript

After creating a program in React TypeScript, I encountered an uncaught error. Despite running and debugging tests and conducting extensive research on Google, I have been unable to resolve this issue on my own. Therefore, I am reaching out for assistance ...

Is there a problem with *ngFor not functioning as expected in Angular 2?

I'm currently working on a project that involves using the GoogleChart. However, I've encountered an issue where only one chart is being created instead of the expected four instances of the GoogleChart. I'm not sure why this is happening as ...

Encountering a Lint error stating "Expected 2 arguments, but received 1" during the testing of the window.scrollBy() function in Jasmine following an Angular

During the upgrade to Angular 11, several other packages, such as jasmine-core, were also upgraded. This caused lint issues when running the 'npm run test' command due to stricter type definitions. One specific issue involves the window.scrollBy ...

Challenges encountered when using npm install in an Angular project

I'm currently working on a project that requires an older version of Angular, specifically version 12.0. I've been attempting to update it to a newer version without success. Whenever I try to install npm, I encounter errors like the one here: ht ...

Efficiently Handling Multiple File Uploads using Angular and Multer

I'm seeking guidance on integrating multer (nodeJS) with Angular 7. Despite trying several solutions, I am unable to successfully upload any files. In my case, the files originate from a ReactiveForm: <mat-tab label="Documents" for ...

ngx-bootstrap tabset draggable tabs

Since 2018, I have been facing an issue that I believe requires a feature request. It is disappointing to see that no progress has been made towards implementing this much-needed feature. Specifically, I am looking to implement a draggable tab within a tab ...

Beginner in Typescript - Exploring ways to verify an interface using an index

When working with a list of operations in a database, each operation may have a unique set of variables that need to be passed. To make adding new operations easier, I decided to store the interfaces within a list structure like this: const operation = { ...