Is it possible to validate a template-driven form without using the model-driven approach?

Attempting to validate a template-driven form in Angular without two-way data binding has proved to be challenging. I have successfully implemented validation using [(ngModel)], but running into an error when trying to validate the form without the MODEL present.

The error message I am encountering is Cannot read property 'invalid' of undefined.

Below is my HTML code:

<div class="jumbotron">
  <div class="container">
    <div class="row">
      <div class="col-md-6 offset-md-3">
        <h3>Angular 6 Template-Driven Form Validation</h3>
        <form name="form" (ngSubmit)="onSubmit(f.value)" #f="ngForm" novalidate>
          <div class="form-group">
            <label for="username">Username:</label>
            <input type="text"
                   class="form-control"
                   name="username"
                   #userName
                   required
                   minlength="8"/>
            <div *ngIf="f.form.controls.username.invalid && f.form.controls.username.touched" class="invalid-feedback">
              <div *ngIf="f.form.controls.username.errors.required" class="alert alert-danger">Username is required</div>
              <div *ngIf="f.form.controls.username.minlength" class="alert alert-danger">length should b 8 character</div>
            </div>
          </div>
     <button class="btn btn-primary" >Register</button>
        </form>
      </div>
    </div>
  </div>
</div>

Additionally, the form is failing to send data to the component when the submit button is clicked.

Here is the TypeScript file for the component:

import { Component, OnInit } from '@angular/core';

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

  // model: any = {};

  onSubmit(f) {
    // alert('SUCCESS!! :-)\n\n' + f);
    console.log(f);
  }
}

Answer №1

Simply update:

f.form.controls.username.invalid

to

username.invalid

while utilizing ngModel

make sure your HTML control looks like this:

<input type="text" ngModel class="form-control" name="username" #username="ngModel" required minlength="8"/>

Answer №2

The reason why it's not functioning is because it was not intended to.

Upon closer examination, it becomes apparent that inputs not linked with ngModel are not included in the form.

By incorporating ngModel, the issue should be resolved.

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

Tips for integrating Typescript Definition files with Visual Studio 2017

I have a challenge with my ASP.NET Core 2.0 application where I am attempting to incorporate TypeScript and jQuery. While TypeScript integration has been successful, I am facing issues with jQuery as it does not provide me with intellisense. Despite trying ...

Passing a generic type as a parameter in a generic class in TypeScript

TypeScript: I have a method in the DataProvider class called getTableData: public static getTableData<T extends DataObject>(type: { new(): T}): Array<T> { ... } Everything works fine when I use it like this: let speakers = DataProvider.getT ...

Incorporating numerous query parameters in Angular version 14

I am currently working on developing a multi-item filter feature for my application and I am faced with the challenge of sending multiple query parameters in the API request to retrieve filtered items. My main concern is whether there is a more efficient ...

Signaling an Event from a module in the node_modules directory to the Vue application

Is there a way to capture an event emitted by a node module and receive it in a Vue file? Sample code from the JavaScript node module: const EventEmitter = require('events') class Find extends EventEmitter { // code snippets here } class Fin ...

Leveraging the p-steps module from PrimeNG for smaller screen sizes

I am facing an issue with resizing the p-steps component from PrimeNG to avoid overflow in smaller screen resolutions. The current code I am using is as follows: <div class="d-flex card mb-4"> <p-steps [model]="items" ...

Steps to assign a JSON file to an array within an object in Angular

What is the best way to assign a JSON file to an array within my "Client" object? I currently have a JSON file named Clients.json with the following structure: { "clients": [ { "firstName": "nameA", "lastName": "lastA", "doctorsNam ...

Utilizing the combination of attribute binding and string interpolation

Looking to create an accordion similar to the one showcased on the Bootstrap website, but with the twist of dynamically loading data using Angular 2's *ngFor directive. I attempted setting the value of aria-controls dynamically like so: [attr.aria-co ...

Obtaining a value using the Node.js inquirer package

I'm currently working on a flashcard generator using the node.js inquirer package, but I'm struggling to capture the user's selection. When the user selects an option, I want to be able to log that choice, but right now it's just return ...

Dynamic Dropdown Menu in Zend Framework with Autofill Feature

I've been diligently working on a code to automatically populate dropdowns onchange, right after selecting the necessary values from an autocomplete search field. However, I am facing an issue where my autofill feature fails to work after making a sel ...

What is the best way to implement a loading cursor when the Submit button is clicked?

Is there a way to incorporate a progress cursor into my code in order to notify the user to wait when they click the Submit button or the Upload Button while uploading multiple files? Below is an example of my form: <form action="" method="post" enct ...

mentioning someone using the @ symbol

I am currently in the process of creating a tagging system for users. I have almost completed it, but there is one issue that I cannot seem to figure out. I know what the problem is, but I am struggling to come up with a solution. When I input the @ sign ...

Using react-google-charts to create visually appealing dual-Y stacked bar charts

I am currently working on developing a bar chart with specific criteria in mind. My data follows the format: [month, region, totalSalesForCompanyA, totalSalesForCompanyB] I have successfully implemented the following charts: A dual-Y bar chart where mo ...

I'm having trouble installing puppeteer

I tried running the command npm i --save-dev puppeteer to set up puppeteer for e2e testing. Unfortunately, an error occurred during installation: C:\Users\Mora\Desktop\JS\Testing>npm i --save-dev puppeteer > <a href="/cd ...

Exploring the Versatility of Axios

Today, I implemented an AJAX request using Axios in JavaScript to submit form data. While the requests are being sent successfully, it seems that the backend is not able to receive the username and password information from the frontend. What could be ca ...

Is there a way to determine if a chosen date and time are prior or subsequent to the current date and time in an AngularJS environment?

When using a datepicker and timepicker, I have obtained a selected date and time. Now, I need to determine if this selected date and time is before or after the current date and time. For example, if the selected date is "Sat Dec 12 2015" and the selected ...

How can we update the form builder or form group in Angular 2 when making changes to the existing data in a table? I'm a bit confused on how to implement router

<tr *ngFor="let row of categories "> <td>{{row.categoryName}}</td> <td>{{row.visible}}</td> <td>{{row.instanceNumber}}</td> <td> <a class="btn btn-info btn-fill " [routerLink]="['/con ...

When passing data to a controller through fetch in Codeigniter 3, the data may sometimes become null

I am facing an issue where I have data that needs to be sent from a view to a controller using fetch, but the data appears as null in the controller despite being successfully sent with a status of 200. Does anyone have a solution to ensure that the data i ...

A guide on setting a default constructor as a parameter in TypeScript

Through collaboration with a fellow coder on StackOverflow, I have mastered the art of specifying a constructor as an argument to a class: type GenericConstructor<T> = { new(): T; } class MyClass<T> { subclass: T; constructor( SubClas ...

The qTip comment box vanishes when focused on by IE/Edge browsers using touch devices

A unique JavaScript library called qTip is being utilized in my project. The application includes a StarRating and Comments feature, both of which are enabled by this plugin. After selecting a rating using the stars, users have the option to add comments, ...

Set an attribute without replacing any existing class attributes

I have developed a script that updates the class attribute of the body element on my website when an option is selected from a dropdown menu. However, I am facing an issue where it overrides the existing dark mode attribute. The purpose of this script is ...