Null errors are encountered when working with Angular 4 Reactive Forms FormControl

When navigating through the text inputs without providing any input, the error message divs are displayed to indicate that the required validator is functioning correctly. However, if I enter anything into one of the fields, an error is immediately thrown by the console:

Cannot read property 'required' of null

Below is the code for my component:

import { PasswordValidators } from './../validators/password.validators';
import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators, FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'app-changepassword-form',
  templateUrl: './changepassword-form.component.html',
  styleUrls: ['./changepassword-form.component.css']
})
export class ChangepasswordFormComponent {

  form;

  constructor(fb: FormBuilder) {
    this.form = fb.group({
      newPassword: ['', Validators.required],
      confirmPassword: ['', Validators.required]
    })
  }

  get newPassword() {
    return this.form.get('newPassword');
  }

  get confirmPassword() {
    return this.form.get('confirmPassword');
  }

}

and here is the HTML:

<form [formGroup]="form">  
  <div class="form-group">
    <label for="newPassword">New Password</label>
    <input formControlName="newPassword" id="newPassword" type="text" class="form-control">
    <div class="alert alert-danger" *ngIf="newPassword.touched && newPassword.errors.required">
      Required
    </div>
  </div>
  <div class="form-group">
    <label for="confirmPassword">Confirm Password</label>
    <input formControlName="confirmPassword" id="confirmPassword" type="text" class="form-control">
    <div class="alert alert-danger" *ngIf="confirmPassword.touched && confirmPassword.errors.required">
      Required
    </div>
  </div>

  <p><button class="btn btn-primary">Submit</button></p>

</form>

Answer №1

Here is where the error stems from:

*ngIf="newPassword.touched && newPassword.errors.required"

Once a value is entered, the errors collection disappears and checking newPassword.errors.required results in the

Cannot read property 'required' of null
error.

An alternative approach would be:

*ngIf="newPassword.touched && newPassword.errors?.required"

To illustrate, consider the following example:

            <div class="col-md-8">
                <input class="form-control" 
                        id="productNameId" 
                        type="text" 
                        placeholder="Name (required)"
                        required
                        minlength="3"
                        [(ngModel)] = product.productName
                        name="productName"
                        #productNameVar="ngModel" />
                <span class="help-block" *ngIf="(productNameVar.touched ||
                                                 productNameVar.dirty || product.id !== 0) &&
                                                 productNameVar.errors">
                    <span *ngIf="productNameVar.errors.required">
                        Product name is required.
                    </span>
                    <span *ngIf="productNameVar.errors.minlength">
                        Product name must be at least three characters.
                    </span>
                </span>
            </div>

Answer №2

Another way to implement this is by using the following syntax without requiring an initial value:

form.get('newPassword').hasError('required')

This code will look for the 'required' error.

An alternative, more concise approach that achieves the same result is:

form.hasError('required','newPassword')

If you are utilizing the AOT option, it's recommended to use the hasError() method as stated in this resource:

Avoid using control.errors?.someError; instead, opt for control.hasError(‘someError’)

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 are some optimal techniques for implementing content-security-policy on an Angular website?

I am currently working on enhancing the security of an Angular website by implementing security headers in IIS. While most of the headers are functioning correctly without any issues, I have encountered a roadblock with the content-security-policy header. ...

How can you specify a "default" value for history.pushState and replaceState?

What value should be used in the title param for browsers to use their default settings? In Safari 5.1.7 (7534.57.2), using either null or undefined as the title param defaults to the browser's settings. However, Opera 12.16 interprets "null" and "u ...

Preventing multiple clicks by toggling the HTML tag on and off

Here is the jQuery structure that I am currently working with: $(document).on('click', '.view-details', function () { $(this).prop("disabled", true); // API call1 // API call2 // API call3 $(this).prop("disabled" ...

Tips for updating the color, background, and height of the particle background using react-tsparticles

Is it possible to customize color and background in react-tsparticles? Below is an example of a particle configuration file named particle-config.js const particlesConfig = { background: { color: { value: "#232741", }, posi ...

Rendering HTML in Vue - Additional loader may be required to manage the output from these loaders

Has anyone encountered this error when trying to dynamically render HTML in Vue (javascript)? Any suggestions on how to resolve it? Module parse failed: Unexpected token (224:36) File was processed with these loaders: * ./node_modules/cache-loader/dist/c ...

The disappearance of UI elements in Angular 13 and Bootstrap 5 when new routes are introduced

After spending a considerable amount of time on website development, I have hit a roadblock with the navigation. Whenever I set up a route, the entire user interface disappears and refuses to load. I have searched extensively but found no solution to this ...

Repeating every 3 to 6 months on later.js commencing from a specified date

Currently, I am working on setting up recurring events every 3 and 6 months using the later.js library which can be found at https://github.com/bunkat/later. The code implementation looks like this: // Assuming my value.scheduled_date is set to 2018-09-0 ...

Adjust the key values within an array of objects in TypeScript

I am looking to update the keys' values of the 1st object within an array of objects. Here is what I have attempted so far: The array of objects: const objArray: FoodItems[] = [ { apple: 4, banana: 7, 'mango & grapes': ...

Error with the jQuery scrolling plugin

Currently, the script is set up this way: jQuery(document).ready(function(){ var windheight = jQuery(window).height(); var windTop = jQuery(window).scrollTop(); var windbottom = windheight + windTop ; jQuery.fn.revealOnScroll = function(){ return this.e ...

The canvas loop list is not displaying for the oscillating image effect

My concept originated when I attempted to create a wave effect using an array of images, but unfortunately, it did not work as expected. The goal was to generate multiple waves in the images by utilizing an array, however, the desired outcome was not achie ...

Hear and register keypress in Angular service

I offer a dialog service Check it out below @Injectable() export class HomeDialogService { public constructor(private readonly dialogService: DialogService, private readonly userAgent: UserAgentService) {} @HostListener('document:keydown.escape ...

What is the best way to change JSON keys on the spot?

I am seeking a way to include escaped quotes around all primary keys within a JSON object. const j = '{"a": "b", "c": "d"}'; let obj = JSON.parse(j); Object.keys(obj).forEach(k => { k = `\"$ ...

Guidelines for simultaneously modifying two dropdown select options

Is it possible to have one dropdown automatically change its value based on the selection made in another dropdown? For instance, if 'Value 1' is chosen from 'dropdown 1', can we set 'dropdown 2' to automatically display the ...

Render a component in certain routes based on specific conditions in React

This is my Index.js ReactDOM.render( <React.StrictMode> <Provider store={store}> <Router> <App className="app-main" /> </Router> </Provider> </R ...

a guide on using ajax to distribute retrieved data among various td elements

After the user presses a button, the data is saved into the database. Upon success, I need to retrieve the data from the database and place it in the appropriate td (in the same row as the clicked td). I've been able to successfully retrieve the data, ...

Enhance website security with X-ray standard user agent

Currently working on a Node.js application and utilizing the X-Ray library along with Request-X-Ray as a driver. I am curious to find out which user-agent X-Ray uses by default. Can anyone provide insights on this? ...

Discover the smallest value in real-time during ng-repeatiteration

In my HTML code, I am utilizing the ng-repeat function. When the user clicks on addBox(), a new input box is appended for adding new data: <div class="col-md-6 col-md-offset-2"> <h5 class="over-title">Variant</h5> <a class="btn ...

Locating the index of the initial duplicate in an array using Javascript

const numbers = [2, 4, 5, 2, 3, 5, 1, 2, 4]; I’m looking to write a function called indexOfRepeatedValue (array) that utilizes the numbers stored in the provided variable. The function should create a variable called firstIndex. Within a for loop, deter ...

Getting React Developer Tools to Function with Webpack

I recently followed a tutorial on how to expose React as a global variable in Webpack using the Expose module. Despite installing the Expose module and adding the appropriate loader configuration in the webpack.config.js file, I am still unable to access R ...

Having trouble accessing store state in Angular with NGXS

In the parent component, I am dispatching an action and hoping to receive the dispatched array in the child component. To achieve this, I have implemented the following code: export class ListComponent implements OnInit { @Select(ProductState.getProductD ...