Angular 8: ISSUE TypeError: Unable to access the 'invalid' property of an undefined variable

Can someone please explain the meaning of this error message? I'm new to Angular and currently using Angular 8. This error is appearing on my console.

ERROR TypeError: Cannot read property 'invalid' of undefined

at Object.eval [as updateDirectives] (RegisterComponent.html:10)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:45259)
at checkAndUpdateView (core.js:44271)
at callViewAction (core.js:44637)
at execComponentViewsAction (core.js:44565)
at checkAndUpdateView (core.js:44278)
at callViewAction (core.js:44637)
at execEmbeddedViewsAction (core.js:44594)
at checkAndUpdateView (core.js:44272)
at callViewAction (core.js:44637)

Here's a code snippet from my register.component.ts file which seems to be related to the errors:

register.component.ts

   import { authTkn } from './../shared/model/loginDetails';
   import { MahasiswaApiService } from './../shared/services/mahasiswa-api.service';
   import { Component, OnInit } from '@angular/core';
   import { Router, RouterModule } from '@angular/router';
   import { FormBuilder, FormGroup, Validators } from '@angular/forms';
   import { first } from 'rxjs/operators';
   import * as CryptoJS from 'crypto-js';
@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.scss']
})

export class RegisterComponent implements OnInit {

  public authTkn: authTkn = null;

  registerForm = this.fb.group({
    user_name: ['', Validators.required],
    fullname: ['', Validators.required],
    telepon: ['', Validators.required],
    email: ['', Validators.required],
    alamat: ['', Validators.required],
    birthdate: ['', Validators.required],
    foto_profil: ['', Validators.required],
    password: ['', Validators.required],
  });


constructor(private mahasiswaApi: MahasiswaApiService, private route: Router, private fb: FormBuilder) { }

ngOnInit() {
  }


onSubmit() {
    this.registerForm.controls.password.patchValue(
      CryptoJS.SHA512(this.registerForm.value.password).toString()
    );
    console.log(this.registerForm.value);
    this.mahasiswaApi.postUserRegister(this.registerForm.value).subscribe(
      res => {
        console.log(res);
        this.authTkn = res;
        console.log(this.authTkn);
        localStorage.setItem('token', this.authTkn.token);
        this.mahasiswaApi.getCurrentToken();
        this.route.navigate(['/home']);
        alert(this.authTkn.info);
      },
      error => {
        console.log(error);
        alert(error.error.message);
      }
    );
  }
}

register.component.html

<div class="login-form">
  <form [formGroup]="registerForm" (ngSubmit)="onSubmit()">
      <h2 class="text-center"> Register </h2>

      <!-- Register Username -->
      <div class="form-group">
          <label for="user_name"> Username </label>
          <input type="text" class="form-control" name="Username" formControlName="user_name" placeholder="text">
          <div class="alert alert-danger" *ngIf="user_name.invalid && user_name.dirty" @myInsertRemoveTrigger>Username Must Be filled</div>
      </div>

      <!-- Register Nama Lengkap -->
      <div class="form-group">
        <label for="nama lengkap"> Full Name </label>
        <input type="text" class="form-control" name="Full Name" formControlName="fullname" placeholder="text">
        <div class="alert alert-danger" *ngIf="fullname.invalid && fullname.dirty" @myInsertRemoveTrigger> Please provide your full name</div>
    </div>

      <!-- Register Phone Number -->
      <div class="form-group">
        <label for="phone_number"> Phone Number </label>
        <input type="text" class="form-control" name="Phone Number" formControlName="telepon" placeholder="text">
      </div>

    <!-- Register Email -->
    <div class="form-group">
      <label for="email"> Email </label>
      <input type="email" class="form-control" name="Email" formControlName="email" placeholder="email">
    </div>

    <!-- Register Date of Birth -->
    <div class="form-group">
      <label for="date_of_birth"> Date of Birth </label>
      <input type="date" class="form-control" name="Date of Birth" formControlName="birthdate" placeholder="date">
    </div>

    <!-- Register Profile Picture -->
    <div class="form-group">
      <label for="Profile_Picture"> Profile Picture </label>
      <input type="file" class="form-control" name="Profile Picture" formControlName="foto_profil" placeholder="file">
    </div>

    <!-- Register Password -->
    <div class="form-group">
      <label for="Password"> Password </label>
      <input type="password" class="form-control" name="Password" formControlName="password" placeholder="password">
      <div class="alert alert-danger" *ngIf="password.invalid && password.dirty" @myInsertRemoveTrigger>Please provide a password</div>
  </div>


      <!-- Submit Button -->
      <div class="form-group">
          <button type="submit" class="btn btn-primary btn-block" [disabled]="!registerForm.valid"> Register </button>
      </div>

      <div class="clearfix">
          <label class="pull-left checkbox-inline"><input type="checkbox" formControlName="remember_me"> Remember me</label>
      </div>
  </form>
</div>

I might have some issues with variable definitions, but I have actually defined arrays of variables used for my form in the beginning of my TypeScript file. However, it seems that something is missing or incorrect. Can anyone help me figure out what it is?

Answer №1

In order to retrieve the form control on the form object, you can use the following code:

registerForm.get('user_name').invalid
. Remember to apply this approach to each property (such as dirty) and for every control within the form.

Alternatively, you can implement a getter in your component class for each form control:

get user_name() {
    return this.registerForm.get('user_name');

This way, you can maintain the existing structure of your HTML.

If you examine the example provided at https://angular.io/guide/form-validation#built-in-validators, it states:

This example introduces several getter methods. Although accessing any form control through the get method on its parent group is always possible in a reactive form, defining getters as shortcuts for the template can be useful.

This pertains to implementing getters for the form controls.

Answer №2

The HTML *ngIf is unable to locate user_name.invalid (same goes for the fullname.invalid) since these are not variables within the component. Although they are listed in the formGroup, it does not mean that a user_name variable is declared at the top of the class.

In order to have user_name, fullname, and password accessible, you will need to declare them as follows:

user_name: string;
fullname: string;
password: string;

After declaring them, you can then populate their values in your code. However, this approach may lead to redundancy when having the same data stored in two different places.

An alternative solution would be using a function to retrieve the value of the control from the formGroup:

getUserName() {
    return this.formGroup.controls['user_name'].value;
} 

It's important to understand that controls defined in a formGroup cannot be displayed in the same manner as accessing a variable via this.

Answer №3

To ensure proper validation, make sure to include the following attribute: #fullname = "ngModel" in the input element that you wish to refer to. Without this attribute, your div element for validation will not recognize the fullname property.

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

Dependency mismatch in main package.json and sub package.json

Imagine you have a project structure in Typescript set up as follows: root/ api/ package.json web/ package.json ... package.json In the main package.json file located in the root directory, Typescript is installed as a dependency to make ...

Exploring ways to create a dynamic background image that allows the rest of the page to float over seamlessly

Currently working on a responsive website and almost done with the build. However, I came across a site where an image appears to be floating behind the rest of the webpage content. Tried searching for a solution using w3.css without any luck. Any sugge ...

Error TS2339: The code is trying to access a property 'f' that is not defined within the 'ReactiveComponent' type

I have recently started working with Angular and I encountered an issue while creating a reactive form. The form is supposed to display the submitted values in an array, but when I added validators to the password field, an error popped up. error TS2339: ...

unable to call a function within Angular

To create a dynamic menu, I am utilizing primeng's menu panel. Firstly, I declare my item variable: items: MenuItem[]=[]; I have two JavaScript objects to incorporate into the menu, namely groupsItem and ejsItem. Here is their structure: groupsI ...

Issues with retrieving data from Firestore and storing it into an array in a React

Struggling to fetch data from my firestore and display it on the webpage. Despite trying all possible solutions and searching extensively, I am unable to get it working. When using the code below, nothing appears on the website. However, if I switch to th ...

Guide on executing get, modify, append, and erase tasks on a multi-parameter JSON array akin to an API within Angular

I have a JSON array called courseList with multiple parameters: public courseList:any=[ { id:1, cName: "Angular", bDesc: "This is the basic course for Angular.", amt: "$50", dur: & ...

Issue with jQuery Cycle causing images not to load in IE all at once, leading to blinking

When using the jQuery Cycle plugin in IE8 (as well as other versions of Internet Explorer), I am encountering an issue. My slideshow consists of 3 slides, each containing a Title, Description, and Image. The problem arises when viewing the slideshow in I ...

Using Angular2: Implementing a single module across multiple modules

Let's delve into an example using the ng2-translate plugin. I have a main module called AppModule, along with child modules named TopPanelModule and PagesModule. The ng2-translate is configured for the AppModule. @NgModule({ imports: [TranslateMo ...

"Angluar4 is throwing an error: it's unable to read the property 'iname' of

This is the code snippet from item.ts file:- export interface item{ $key?:string; available?:boolean; countable?:boolean; iname?:string; price?:string; desc?:string; image?:string; } The items component item.componenet.ts looks like this:- import { Com ...

Executing a function simultaneously in two separate tabs using Angular

I need to conduct a specific test within my web application that requires opening two separate tabs in my browser and running the application in both tabs simultaneously. My goal is to execute the same function at the exact time in both tabs (for example, ...

What is the best way to set up a reactive form in Angular using the ngOnInit lifecycle

I have been facing an issue while trying to set up my reactive form with an observable that I subscribed to. Within the form class template, I used the ngOnInit lifecycle hook to fetch the desired object, which is the product. The first code snippet repre ...

Navigating through JSON data in an Angular application

I am currently facing an issue with uploading and parsing a JSON file in my Angular application. The problem lies in the fact that even though I can successfully upload the file, I am unable to access the data from it. To ensure the correct file is being ...

Is it possible to interchange the positions of two components in a routing system?

driver-details.component.ts @Component({ selector: 'app-driver-details', templateUrl: './driver-details.component.html', styleUrls: ['./driver-details.component.css'] }) export class DriverDetailsComponent implements OnI ...

Images that dynamically adjust within the confines of a single div

My issue involves a simple script that includes two responsive images. When the window is minimized, the images adjust accordingly. However, when I place both images within the same div like this: <div class="wrapper"> <div class="block"&g ...

No contains operator found in Material UI Datagrid

While working on a project, I utilized Material UI's datagrid and successfully implemented filters such as contains and isEmpty. However, I am struggling to find information on how to create a notContains filter. Does Material UI natively support this ...

It is not always a guarantee that all promises in typescript will be resolved completely

I have a requirement in my code to update the model data { "customerCode": "CUS15168", "customerName": "Adam Jenie", "customerType": "Cash", "printPackingSlip": "true", "contacts": [ { "firstName": "Hunt", "lastName": "Barlow", ...

"Unexpected discrepancy: Bootstrap Glyphicon fails to appear on webpage, however, is visible

I am having some trouble getting the glyphicon to display properly in my side nav. The arrow head should rotate down, which is a pretty standard feature. Here is the link to the page: The glyphicon should be visible on the "Nicky's Folders" top leve ...

What is the best way to manage the back button functionality on pages that use templates?

I am currently developing a website using angularjs. The layout consists of two main sections: the menu and the content area. For instance This is an example page: /mainpage <div> <div id="menu"> <div ng-click="setTemplate('fi ...

The HTML code as content

While working on an AJAX project, I ran into this issue: http://jsbin.com/iriquf/1 The data variable contains a simple HTML string. After making the AJAX call, I noticed that the returned string sometimes includes extra whitespaces. I attempted to locat ...

The delay function in RxJS allows for waiting to return a value until a specific condition is met within a stream and

Currently, I am facing an issue with a method in my application that triggers a server request. This method has access to a stream from the redux-store and needs to execute a callback only when the result of the request is found in the mentioned stream. Th ...