Angular - Unable to access property '$invalid' because it is null

Working on my login page with angular and typescript. Clicking the submit button should trigger the login function in the controller, but if the form is invalid, it should just return.

New to typescript, I keep running into an error when trying to add an if statement to check if the form is invalid:

Cannot read property '$invalid' of undefined
.

Here's the HTML:

<form class="login-form" name="loginForm" ng-submit="vm.login()" novalidate>
     <input type="email" name="email" placeholder="Email" required ng-model="vm.email" ng-class="{true: 'input-error'}[submitted && loginForm.email.$invalid]"/>
     <input type="password" name="password" placeholder="Password" required ng-model="vm.password" ng-class="{true: 'input-error'}[submitted && loginForm.password.$invalid]"/>
     <input type="submit" id="submit" ng-click="submitted=true"/>
</form>

And here's the compiled javascript:

var LoginModule;
(function (LoginModule) {
    var LoginController = (function () {
        function LoginController() {
        }
        LoginController.prototype.login = function () {
            if(this.loginForm.$invalid) {
                return;
            }
            console.log("Login was clicked, email is " + this.email + " and password is " + this.password);
        };
        return LoginController;
    })();
    LoginModule.LoginController = LoginController;
})(LoginModule || (LoginModule = {}));
angular.module('loginModule', []).controller('LoginController', LoginModule.LoginController);

Seems like the issue isn't with specifying the form name, as some have suggested. Anyone have insight on why this error might be occurring?

Answer №1

Make sure to include the controller alias within the form tag

<form  name="vm.loginForm" ng-submit="vm.login()" novalidate>

Answer №2

Although @charlietfl's response was accurate for the original poster's query, this particular error may arise when the ng-model attribute is overlooked on an input element and the ui.bootstrap.showErrors method

$scope.$broadcast('show-errors-check-validity')
is being utilized.

According to the official documentation (highlighting mine):

.. an input control that utilizes the ngModel directive contains an instance of NgModelController. This control instance can be exposed as a property of the form instance by using the name attribute in the input control. The name attribute specifies the property name on the form instance.

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

Exploring the connection between Django and AngularJS: delving into the router functionality and how Django variables are assigned

As a beginner in IONIC, AngularJS, and Django, I recently attempted to host an IONIC project within Django. While both Django and AngularJS are excellent frameworks individually, integrating them has left me feeling confused. Question 1: How can I effecti ...

Combine multiple objects to create a new object that represents the intersection of all properties

Imagine you have these three objects: const obj = { name: 'bob', }; const obj2 = { foo: 'bar', }; const obj3 = { fizz: 'buzz', }; A simple merge function has been written to combine these three objects into one: ...

"Troubleshooting: Why isn't AngularJS $http.post sending my data

Feeling frustrated with my experience using AngularJS and Laravel 5.2. I'm trying to make a standard $http post request: APIservice.saveArticle = function ( oArticle, callback ) { var message = 'Hello World!'; $http({ metho ...

How to Use a For Each Loop with Google Maps DrawingManager to Create Polygons?

My Ionic 4 Application using Angular 8 incorporates a google maps component where I need to draw and edit multiple polygons, eventually saving their vertices in a database. Hard coding some polygons is easy with getPath() or getPaths(), but I'm utiliz ...

Determine the data type of a property by referencing the data type of another property within an array of objects using TypeScript

I am working with a specific type of interface called Route that consists of name and path properties. interface Route { name: string, path: string } const routes = [ { name: "first", path: "/first" }, ...

Enhance user experience by implementing a feature in AngularJS that highlights anchor

As I am in the process of developing a chat application using Angular, I have encountered an issue with switching between views. One view, named 'chat.html', displays the list of available users while another view, 'chatMessages.html', ...

Utilizing a Typescript class interface does not maintain the original method types

Struggling to define a Typescript interface and implement it in a class. The issue lies in the method signatures of the interface not being applied to the class as expected. Below is a simplified example: export interface Foo { bar(value: string): voi ...

Tips for effectively navigating with the `Next-intl` and `next/link` componentsWhen working with the

I have implemented a next-intl library to enable multi-language support on my website. This means that the paths for different languages look like www.next.com/de or www.next.com/en Currently, I am utilizing NextJS 14. <NextLink href="/support-us& ...

I will evaluate two arrays of objects based on two distinct keys and then create a nested object that includes both parent and child elements

I'm currently facing an issue with comparing 2 arrays of objects and I couldn't find a suitable method in the lodash documentation. The challenge lies in comparing objects using different keys. private parentArray: {}[] = [ { Id: 1, Name: &ap ...

Error message: In my router module, Angular's 'Subject' is not subscribed to

Currently, I am utilizing a canActivateFn guard in my application where I am subscribing to a Subject. This particular Subject was instantiated in a separate service, and I'm perplexed as to why the subscription does not seem to trigger (the callback ...

What causes an ObjectUnsubscribedError to be triggered when removing and then re-adding a child component in Angular?

Within a parent component, there is a list: items: SomeType; The values of this list are obtained from a service: this.someService.items$.subscribe(items => { this.items = items; }); At some point, the list is updated with new criteria: this.some ...

Customize the position values of the Ngx-bootstrap Tooltip manually

I have incorporated ngx-bootstrap into my Angular 4 application. The component I am using is ngx-bootstrap Tooltip: After importing it, I am implementing it in my component's view like this: <button type="button" class="btn btn-primary" ...

Using jscodeshift, transform all named import statements to default import statements for MUI V5

I'm in need of assistance with a jscodeshift script to convert all named imports to default imports for Material-UI version 5 using React and Typescript. import { Button, TextField } from '@mui/material'; The desired result should be: impor ...

Is there a way to access the value or key of a JSON property in an Angular template for rendering purposes?

Having trouble displaying the JSON values of certain properties on screen. Utilizing Angular Material table to showcase my JSON response. The code snippet below is responsible for rendering the JSON data: <mat-card-content class="dashboard-card-cont ...

AngularJS - Use promise instead of returning a data object

I am currently working on a project using AngularJS. Within my service.js file, I am attempting to retrieve some values. However, instead of receiving the actual data, I am getting back a promise object with some $$variables along with the desired data. ...

Ways to transfer specific properties from one object to another in TypeScript

I'm currently working on a function that selectively copies key-value pairs from one object to another in order to remove certain properties. The code snippet for this function is shown below: sanitizeData: function (sourceObject: object, ...allowedKe ...

Expanding the property of an established type to a nested type

Let's talk about titles. Well, maybe not this one. I tried to come up with a good title, but it didn't work out as planned. In my coding journey, I have created a cool interface called DefaultTheme: export interface DefaultTheme { colors: ...

Ways to access the new value of a cell in a Material UI Datagrid through the use of GridCellParams

When trying to access the newly modified value in a cell using the GridCellParams interface, I am faced with the issue that the 'value' property only provides me with the previous value of the cell. This asynchronous behavior is not ideal for my ...

Retrieve information using AngularJS only when it is not yet defined

Currently, I am using $http in a controller to retrieve data and display it to the user. However, once the data is fetched for the first time, I do not want to fetch it again when moving between different tabs or controllers. My expertise lies in web dev ...

Issue with Material UI: Unable to utilize import statement outside of a module due to Select dependency

Hello there! Here is my query: I am currently working on a project using NextJS + React with node. Everything seems to be running smoothly, except for one issue I encounter when reloading a page with a Select component from Material UI. The relevant code ...