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

What is the best way to design an angular directive or service specifically for straightforward pagination featuring only next and previous options?

Within a block of div tags, an ng-repeat directive is being used to display sets of 3 divs at a time. By clicking on the next button, the next set of 3 divs should be displayed, and the same goes for the previous button. Check out the HTML code below: &l ...

Guide on packaging an Angular 2 Typescript application with Gulp and SystemJS

In my Angular 2 project, I am using Typescript with SystemJS for module loading and Gulp as a task runner. Currently, the project is running on Angular RC2 but the same issue persists with RC1. I followed the steps provided in brando's answer here. U ...

Steps for transferring data between two components

I'm looking for a way to transfer an object's id from one component to another. <ng-container matColumnDef="actions"> <mat-header-cell *matHeaderCellDef></mat-header-cell> <mat-cell *matCellDef="let user"> ...

Error: Undefined Function [Thinkster.io's Angular Tutorial Chapter 4]

Currently working on the Angular Tutorial provided by Thinkster.io and enjoying every bit of it. However, I've hit a roadblock in Chapter 4 that seems impossible to overcome. Whenever I attempt to execute a Post or Delete action, I encounter the follo ...

Would it be considered bad practice to utilize ng-init for executing a function in the controller upon the view being loaded?

For easier testing, I have started initializing my controllers using ng-init. So in my controller, you'll find code like this: $scope.initiate = function () { myResource.makeXhrRequest(); } And in my view, it looks like this: <div data-ng-i ...

Why styled-components namespace problem in React Rollup build?

I designed a "UI Library" to be utilized in various projects using ReactJS + TypeScript + styled-components and Rollup. However, I am currently encountering issues with conflicting classNames. I am aware that styled-components offers a plugin for creating ...

Is there a way to efficiently parse HTML data returned as JSON in the browser using Cordova/Ionic?

Currently, I am retrieving data from a Drupal service and using AngularJS along with the ionic framework to create a hybrid app for mobile platforms, leveraging Cordova or Phonegap. You can check out my code on codepen: http://codepen.io/BruceWhealtonSWE/p ...

What is the best way to update $state in AngularJs when the user makes changes to the controller?

I am currently working on Angular UI Router and I want to refresh the current state by reloading it and rerunning all controllers for that state. Is there a way to reload the state with new data using $state.reload() and $stateParams? Here is an example ...

Navigating with the Angular router leads to an unexpected destination: "mat-radio-group-0=true"

I'm facing an issue with a close button in my HTML template that triggers a close() function in the component: HTML template: <div> <label id="radio-group-label">Please specify: </label> <mat-radio-grou ...

AngularJS menu - track the selected item and highlight it as active

Why isn't the menu item highlighted when clicked on? Check out the screenshot below: https://i.stack.imgur.com/ZLZAG.png <div ng-controller="DropdownCtrl as ctrl"> <md-menu> <md-button aria-label="Menu" class="md-ic ...

Transferring Data from View to Controller to Service in AngularJS

I've reviewed similar inquiries, but none seem to make much sense. I have a web API that is used for user logins. Users input their username and password, which then triggers an API query returning data to determine whether the login should proceed or ...

Error: The property 'open' is not defined in the mdMenu object

Encountered a bug while working with angular-material design... When using md-menu, if a sub menu item is opened (as shown in the image) and then hovering over a non-subMenu item (menu item), it throws an error "Cannot read property 'open' of nul ...

The skin colors are failing to load on JWPlayer7

I've encountered a strange issue with jwplayer. I'm setting it up from an Angular JS Controller and loading it using a simple preview button that loads the jwplayer with the specified configuration. It should be straightforward. jwplayer(id).s ...

Building and executing an Angular 2 program on the Windows platform: Step-by-step guide

After successfully installing npm and related packages including TypeScript and Angular 2, I am encountering difficulties running Angular 2 in my browser on a Windows platform. Can someone provide a step-by-step guide to help me create and run Angular 2 ...

The problem with the onClick event not triggering in Angular buttons

My issue revolves around a button in my code that is supposed to trigger a function logging the user out. However, for some reason, the event associated with it doesn't seem to be functioning at all. Here's the relevant code snippet: TS File: imp ...

Enhancing the D3.js chart with tooltip, x-axis, and y-axis titles

I am looking to enhance the graph by adding a tooltip that displays information on the Y-axis value, time to the circle, and titles for both the X-axis and Y-axis. I attempted to implement this functionality within svg.selectAll but encountered difficultie ...

Checking for GitHub API connectivity issues with GitHub can be done by verifying whether the GitHub API is

Is there a way to check from the GitHub API if it is unable to connect to GitHub or if the internet is not connected? When initializing the API like this: GitHubApi = require("github"); github = new GitHubApi({ version: "3.0.0" ...

Ways to showcase the content of a page once the controller variables have been set

As someone who is just starting out with AngularJS and web development, I am curious to know if there is a way to delay the display of a page until after all of the controller's $scope variables have been initialized. Most of my $scope variables are c ...

Access to the 'currentUrlTree' property is restricted to the 'Router' class as it is marked as private and cannot be accessed externally

Currently, I am in the process of developing a login feature using jwt. However, I am encountering an error when attempting to retrieve the current URL of the active route as shown below. Error Message: [default] /Users/~/src/app/app.component.ts:51:75 P ...

Generating ambient module declarations in Typescript for distribution on NPM

Seeking advice on generating TypeScript ambient module declarations for a node (commonjs) npm package being developed in TypeScript. Encountering confusion around the proper method to have TypeScript create these ambient module declarations for node / comm ...