Angular 8 template-driven form encountering a Minimum Length Error

Upon clicking the submit button, I encountered the following error:

ERROR TypeError: Cannot read property 'minlength' of null

I am unsure why this error is happening. How can I go about resolving this issue?

Below is the code from app.component.html:

<form name="form" (ngSubmit)="f.form.valid && onSubmit()" #f="ngForm" novalidate>
<div class="form-group">
                <label for="categoryName">Category Name:</label>
                <input type="text" class="form-control" name="categoryName" [(ngModel)]="cate.categoryName" minlength="5" #categoryname="ngModel" [ngClass]="{ 'is-invalid': f.submitted && categoryName.invalid }" required/>
                <div *ngIf="f.submitted && categoryName.invalid" class="invalid-feedback">
                    <div *ngIf="categoryName.errors.required">
                        Category Name is required
                    </div>
                </div>
                <div *ngIf="categoryName?.touched && categoryName?.errors.minlength" class="invalid-feedback">
                    Category Name must be at least 5 characters long.
                </div>
            </div>
</form>

Answer №1

It seems like the error is originating from a specific line of code that you provided:

<div *ngIf="categoryName?.touched && categoryName?.errors.minlength" class="invalid-feedback">

The issue here is that categoryName?.errors is null, and you are trying to access minlength on this null value.

To prevent this error from occurring, you should use the safe navigation operator ? before accessing .minlength, like so:

<div *ngIf="categoryName?.touched && categoryName?.errors?.minlength" class="invalid-feedback">

Answer №2

<div *ngIf="categoryName.touched && categoryName.errors?.['minlength']" >Error: Category name must be at least X characters long</div>

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

Kindly include an @Ionic3Annotation for either @Pipe, @Directive, or @Component

During development, this code runs without any issues. However, when attempting to run it in production using the command: Working: ionic cordova run android Not working: ionic cordova run android --prod --release Error Message: [03:34:41] types ...

Step-by-step guide to developing an Angular 2+ component and publishing it on npm

I need assistance with creating an AngularX (2+) component and getting it published on npm. My objective is to publish a modal component I developed in my current Angular App, though currently, I am focusing on creating a <hello-world> component. It ...

What is the best method to publish my npm package so that it can be easily accessed through JSDelivr by users?

I've been working on creating an NPM package in TypeScript for educational purposes. I have set up my parcel configuration to export both an ESM build and a CJS build. After publishing it on npm, I have successfully installed and used it in both ESM-m ...

I'm running into an issue where my API calls are being duplicated

Every time I refresh the page, the network preview displays a duplicate API call to (ipaddress)/(portnumber)/admin/user-group?page=1&page_size=10&query= twice. I've tried making changes to the useEffect() and handleSearch() functions without s ...

Storing data in GridFS with MongoDB from an express buffer

Currently, I am attempting to save an Image file that I'm sending as multipart in my MongoDB utilizing GridFS. My approach involves using multer with the memoryStorage option. let upload = multer({ storage: multer.memoryStorage() }).single('ima ...

Tips for accessing data from a local JSON file in your React JS + Typescript application

I'm currently attempting to read a local JSON file within a ReactJS + Typescript office add-in app. To achieve this, I created a typings.d.ts file in the src directory with the following content. declare module "*.json" { const value: any; ex ...

shared interfaces in a complete javascript application

In the past, I have typically used different languages for front-end and back-end development. But now, I want to explore the benefits of using JavaScript/TypeScript on both sides so that I can have key data models defined in one central location for both ...

What is the best way to include an object in a document before sending it back?

I am facing a challenge that involves retrieving data from Firestore using angularfire. Once I fetch a collection, I need to iterate through each document in the collection and then make a separate request to Firestore to get additional document values. Th ...

What is the method for implementing type notation with `React.useState`?

Currently working with React 16.8.3 and hooks, I am trying to implement React.useState type Mode = 'confirm' | 'deny' type Option = Number | null const [mode, setMode] = React.useState('confirm') const [option, setOption] ...

Exploring Ngu-Carousel in Angular 7: Importing JSON data for a dynamic display

After attempting to import data from JSON and display it using ngu-carousel, I encountered an error. The error shows "length of undefined" Subsequently, when I try to click on the previous/next button, another error appears. This error states "innerHTML ...

Using object bracket notation in TypeScript to retrieve values from props with the help of string interpolation

I encountered an issue in my code while attempting to utilize a variable within my TSX component. This problem arises due to the dynamic props being passed into the component, which are always a string that matches one of four keys in the "characters" obje ...

Exploring unit tests: Customizing an NGRX selector generated by entityAdapter.getSelectors()

Let's imagine a scenario where our application includes a books page. We are utilizing the following technologies: Angular, NGRX, jest. To provide some context, here are a few lines of code: The interfaces for the state of the books page: export int ...

Encountering a TypeScript type error when returning a promise from a function

I currently have a scenario in which there is a function that checks if user whitelisting is required. If not, it calls the allowUserToLogin function. If yes, it then checks if a specific user is whitelisted. If the user is not whitelisted, an error is thr ...

The change handler of the TS RadioGroup component, instead of returning an array of possible strings, returns a unique

My interface declaration for StopData is shown below: export interface StopData { stopName: string, stopType: 'stop' | 'waypoint' } I have implemented a radio group to choose the 'stopType', which consists of two radi ...

Children must be matched to the route before navigating to it

Hello there! I'm having trouble understanding how to navigate new routes with children in Angular 2 rc 4. I'm trying to route to the TestComponent, which has a child, but I keep getting an error message saying "cannot match any route 'test&a ...

What possible reasons could cause the installation of Visual Studio 2017 to disrupt node.js or the typescript compiler?

Recently, I updated to the latest version of Visual Studio 2017 and selected the node.js support option during installation. However, after this update, I encountered issues with the typescript compiler (tsc) in an Angular 2 project that was last modified ...

The type 'MockStoreEnhanced<unknown, {}>' is not compatible with the type 'IntrinsicAttributes & Pick[...]

I'm currently working on creating a unit test for a container in TypeScript. From what I've gathered from various responses, it's recommended to use a mock store and pass it to the container using the store attribute. This method seems to o ...

Node.js does not allow the extension of the Promise object due to the absence of a base constructor with the required number of type

I'm trying to enhance the Promise object using this code snippet: class MyPromise extends Promise { constructor(executor) { super((resolve, reject) => { return executor(resolve, reject); }); } } But I keep encou ...

There seems to be an issue with executing an imported function from a .ts file within a TSX file in NextJs, resulting

I've encountered an issue that seems to be related to using NextJs with TypeScript. For example: // /pages/index.tsx import _ from 'lodash' export const MyComponent = () => { return ( <ul> { _.map(someArray, ...

Utilizing Typescript to define key-value pairs within a structured form

I've been creating a form structure that's functioning smoothly, but I've encountered an interesting issue with field validation in the validation part. While my Visual Code is pointing out that 'required2' in the phone constant n ...