Ways to usually connect forms in angular

I created a template form based on various guides, but they are not working as expected. I have defined two models:

export class User {
  constructor(public userId?: UserId,
              public firstName?: String,
              public lastName?: String,
              public address?: Address) {
  }
}

export class Address {
  constructor(
    public street?: String,
    public city?: String,
    public zipCode?: String) {
  }
}

Here is the component I am using:

Component({
  templateUrl: 'user.html'
})
export class MyComponent implements OnInit, OnDestroy{
  user: User;
  userForm: NgForm;
  ngOnInit(): void {
  }

Below is the code snippet of the page itself:

<form novalidate #userForm="ngForm">


    <div class="form-group">

        <input required minlength="4" type="text"
               id="firstName"
               [(ngModel)]="user.firstName" name="firstName">
        <small *ngIf="!firstName.valid">Not valid!</small>
    </div>
    <div class="form-group">
        <input required ng-minlength="4" type="text"
               id="lastName"
               [(ngModel)]="user.lastName" name="lastName">
    </div>

    <div ngModelGroup="user.address">
        <div class="form-group">
            <input required ng-minlength="4"
                   type="text"
                   id="address-house"
                   [(ngModel)]="user.address.address1" name="address.address1">
        </div>

        <div class="form-group">
            <div class="form-group">
                <input required ng-minlength="4"
                       type="text"
                       id="zipCode"
                       [(ngModel)]="user.address.zipCode" name="address.zipCode">
            </div>
            <div>
                <input required ng-minlength="4"
                       type="text"
                       lass="form-control input-lg"
                       id="city"
                       [(ngModel)]="user.address.city" name="address.city">
            </div>
        </div>

    </div>
    <button type="button" (click)="checkAndProceed()">Continue</button>
    </div>
</form>

I am looking to add validation to this form, but so far none of the resources I've looked at have been helpful. Is it possible to implement validation in HTML or TypeScript? Specifically, I want the validation to trigger when the 'Continue' button is clicked and only proceed if the form is valid.

When attempting to validate, I encountered this console error:

Cannot read property 'valid' of undefined

Answer №1

Input elements have various attributes such as name, Id, and template reference variable. Your current code lacks the inclusion of the template reference variable. This variable is responsible for holding the reference to the element along with flags like valid and dirty.

To rectify this, modify your code to incorporate a template reference variable in this manner:

<div class="form-group">
    <input required minlength="4" type="text"
           id="firstName"
           [(ngModel)]="user.firstName" name="firstName"
           #firstNameVar="ngModel">
    <small *ngIf="!firstNameVar.valid">Not valid!</small>
</div>

Note the #firstNameVar used as the template reference variable. It can share the same name as your Id and name attributes, however, I've opted for a distinct name for clarity.

Also, observe that the *ngIf statement now utilizes firstNameVar.valid instead.

For further insights on template reference variables, refer to: https://angular.io/guide/template-syntax#ref-vars

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 the steps to testing a webpage designed for Retina display?

I have designed a webpage optimized for retina display, but I don't own a monitor with that capability. Is there a simulation tool available to test websites on retina displays? Alternatively, are there non-Apple monitors comparable to Apple's ...

Converting to alphanumeric characters using JavaScript

Is there a way to efficiently encode a random string into an alphanumeric-only string in JavaScript / NodeJS while still being able to decode it back to the original input? Any suggestion on the best approach for this would be greatly appreciated! ...

What is the reason for using a callback as a condition in the ternary operator for the Material UI Dialog component?

I am in the process of reconstructing the Material UI Customized Dialog component based on the instructions provided in this particular section of the documentation. However, I am unable to grasp the purpose behind using a callback function onClose conditi ...

What is the most effective method to exhibit every element within a content wrapper at a specific interval of time?

I am looking for a way to display each div within the content-wrapper after a specific time interval. Currently, I am using individual classes like el1, el2, el3, ... to accomplish this task. However, when dealing with content-wrappers containing multipl ...

Am I making a mistake in my implementation of sending Socket.io messages to a designated room?

Upon a user joining, I alter their ID to a shortened random code. This change is made to utilize the id as a visible session ID on the front-end. I mention this to prevent confusion regarding non-standard socket IDs and their relation to potential issues. ...

Added the .active state to the menu navigation successfully, however the active color was not implemented

My primary navigation menu is managed by WordPress and can be seen below. I aimed to modify the active state when a user clicks on a link in the menu by adding background-color and color for styling purposes. Although changing the background-color upon cl ...

Incorporating middleware in Next.js to remove route protection

Looking to remove the protection for the login page, and here is how my folder structure looks: https://i.stack.imgur.com/klPYV.png This is the middleware I am using: import { NextResponse, NextRequest } from "next/server"; export async functi ...

Oops! The formGroup function in Angular 5 requires an instance of a FormGroup

While working with Angular 5, I encountered an error in this basic form. Here is the issue: Error Message: EditVisitanteDialogComponent.html:10 ERROR Error: formGroup expects a FormGroup instance. Please pass one in. Example: > > &l ...

Extension for Chrome that enhances YouTube video playback experience

I'm struggling to figure out why this isn't functioning. I've reviewed the Google extension dev docs and examined some sample code. Checked various Stack Overflow questions and answers, but haven't received any helpful feedback or res ...

What could be causing the TypeError I encounter when trying to import @wordpress/element?

Encountering a similar issue as discussed in this related question. This time, I've switched to using '@wordpress/element' instead of 'react-dom/client' based on the recommendation that it also leverages React functionalities. Ho ...

Change the value of a single element in an array using a component in ReactJS

I'm attempting to pass an array value to a specific index in one component and then assign a desired value from the child component. I need it to work this way because I'm developing a survey app where the number of questions can vary. This is j ...

What is preventing me from using jQuery to dynamically insert HTML onto the page?

Below is the HTML code for a Bootstrap Modal dialog box: <div class="modal fade" id="rebateModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> ...

Choosing and Duplicating Text in Angular

I'm attempting to give the user the ability to select a paragraph and copy it by clicking a button. However, my current code is not working as expected. I initially tried importing directives but encountered errors, prompting me to try a different met ...

Is it normal for Tailwind animation to loop twice when transitioning between pages in Next.js?

I'm currently utilizing react-hot-toast for displaying alerts and animating them during page transitions. The animation involves a double fade-in effect when transitioning between pages. In my project, I've integrated tailwindcss-animate within ...

Discovering latitude and longitude coordinates from a map URL, then enhancing dynamism by utilizing the coordinates as parameters

Hello, I am currently learning Vue.js and have encountered a challenge with embedding Google Maps URLs. Despite my extensive research on Google, I have not been able to find the solution I need. Here is an example of the URL I am working with: "https: ...

Validation of input using JQuery

I am currently working on validating a form, with a specific field that needs to be required. Here is the code for the field in question: <p> <label for="lf">Name: </label> <input class="lf" name="name" type="text"/> < ...

Ways to block WebSocket access on a personal computer

Is it possible to protect my server resources from being accessed by other websites, such as example.com, via WebSocket? I want to prevent them from accessing the server using a URL like "ws://47.80.151.189:1234", and utilizing its resources (bandwidth, me ...

Unable to display the absolute path of the image src in WebStorm

Hey there! I recently started learning HTML5 and have been using WebStorm on my trusty Macbook Air for about two weeks now. I've encountered a problem with image sourcing that has left me puzzled. Here's my question: Why is it that images from ...

Widget for navigating through Youtube videos

I am currently working on creating a widget that allows users to navigate a YouTube video using buttons. For instance, if the video is of a car race, there would be buttons labeled Lap 1, Lap 2, and so forth. My idea involves adding an extension to the vi ...

Increasing the size of a div container based on the position of the cursor on the

I recently stumbled upon a fantastic website where two images slide left and right based on mouse movement. When the cursor is on the right, the right part of the image expands, and when it's on the left, the left part expands. You can check out the ...