Validating Forms in TypeScript

Currently in the process of learning Angular 10, but encountering a challenge

I have an HTML document that validates a form group in my component. When I set a value for a textbox from my component, the value is displayed correctly, but my submit button claims it is invalid (required).

Allow me to demonstrate....

Component

 export class PersonalComponent implements OnInit {

  personalForm = new FormGroup({

      name: new FormControl('', Validators.required),
      email: new FormControl('', [Validators.required,
      Validators.pattern("^[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,4}$")])
    });
 public name: string = '';
 public email: string = '';
 public submitted = false;

Method

  getPersonalData() {
    this.activatedRoute.params.subscribe(prm => {
        this.service.getPersonal(prm['id']).subscribe(data => {
          this.name = data.name;
          this.email = data.email;
        },
          err => {
            console.log(err);
          });
    })
  }

Save method

onSave(form: Personal) {
    this.submitted = true;
    if (this.personalSaveForm.valid) {
      this.service.postPersonal(form).subscribe(data => {
        console.log('saved');
      },
        err => {
          console.log(err);
        });
    }
  }

HTML document

<form [formGroup]="personalSaveForm" (ngSubmit)="onSave($event)">

 <div class="col-sm-3">
            <label for="name" class="col-form-label">Name</label>
          </div>
          <div class="col-sm-3">
            <input type="text" id="name" value="{{name}}" [ngClass]="{'form-submitted': submitted}" formControlName="name" class="form-control" required />
          </div>

 <div class="col-sm-3">
            <label for="email" class="col-form-label">Email</label>
          </div>
          <div class="col-sm-3">
            <input type="text" id="email" value="{{email}}" [ngClass]="{'form-submitted': submitted}" formControlName="name" class="form-control" required />
          </div>

      <div class=" col-sm-12 align-items-right">
        <button type="submit" id="btnSave" class="btn btn-primary" style="float: right;">Next</button>
      </div>

As can be observed, even though the component sets a default value for the textbox, the validation persists when the button is clicked!!! despite having a value!

Thank you

Answer №1

It appears that there are some errors in your code:

<div class="col-sm-3">
   <input type="text" id="email" value="{{email}}" [ngClass]="{'form-submitted': submitted}" formControlName="name" class="form-control" required />
</div>

The formControlName should be changed to email to match the FormGroup value.

If you are using Validators.required, there is no need to include required in your HTML since the programmatic validation already covers it. Additionally, avoid directly inserting values into the input as it may conflict with the formControl value.

To set the value of your form control in component.ts, use this syntax:

this.personalSaveForm.get('name').setValue('New Name')

If you need to bind a variable directly to an input, consider using template-driven ngModel (although not preferred).

Keep in mind that '' evaluates to falsy in JavaScript, so setting it as a default value will result in the form being invalid by default.

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

Why does Material-UI's "withStyles()" not function properly with a specified constructor in Typescript?

Update: Please note that there was an issue with the constructor generated by IntelliJ IDEA, but it has been fixed. You can find more details here: I'm exploring the use of Material-UI in my application, and I've encountered some challenges wit ...

Firebase - Accessing data for a specific item

Apologies for the lengthy question. I have a collection of events that I retrieve like this: export class HomePageComponent implements OnInit { events: FirebaseListObservable<EventModel[]>; constructor( private authService: AuthService, ...

Tips for utilizing string interpolation in the style tag of an Angular component

@Component({ selector: 'app-style', template: ` <style> .test { color: {{ textColor }} } </style> ` }) export class StyleComponent { textColor = "red"; } The current method doesn't appear to b ...

Managing the outcome of numerous asynchronous calls before accessing the database post-result collection

Hey everyone, I'm just getting started with node.js and I'm working on the following tasks: Calling the AWS API to create Cognito users by passing data. After all requests are completed, inserting all the records into the database. In my code, ...

What is the best way to conceal the header and search component in a different component by utilizing navigation?

Current Situation: I am currently dealing with two components (app-header and app-search) that are both included in app.component.html as follows: <app-header></app-header><app-search></app-search> Additionally, I have set up navi ...

TS Intellisense in Visual Studio Code for JavaScript Events and File Types

Whilst attempting a similar action, onDragOver(event: Event): void in Visual Studio Code, an error is thrown by IntelliSense: [ts] Cannot find name 'Event'. The same issue arises when trying something like this: let file: File = new File() ...

Trouble accessing files in the assets folder of Angular 2

I am encountering a 404 error when attempting to access a local file within my application. I am unable to display a PDF that is located in a sub-folder (pdf) within the assets folder. I am using CLI. <embed width="100%" height="100%" src="./assets/pdf ...

Issue: React child components cannot be objects (received: object with keys)

Hey everyone, I could really use some help figuring out what I'm doing wrong. Here is the error message I'm receiving: Error: Objects are not valid as a React child (found: object with keys {id, title, bodyText, icon}). If you meant to render a ...

How can we eliminate the modal-open class in Angular when transitioning to a different URL?

Currently, I am facing an issue with a bootstrap modal. There is a button inside the modal which upon clicking should navigate the current component to another component named 'questions'. The problem arises when the new component is loaded, as t ...

The mat select option does not have the correct width for the mat

Can someone please help me with this issue? I'm having trouble with the width of the options in a mat-select within a form. When I try to select an option, the width extends to 100% instead of staying within the select box. Here is a snapshot showing ...

I'm curious, where does Visual Studio create the dist folder when you run an Angular Web Application?

Currently utilizing Visual Studio 2019 Community Edition, although the same situation also pertains to VS2017 and other editions of 2017/2019. While developing/running an ASP.NET Core Web Application with an Angular web project, I'm unable to locate ...

Filtering a Table with Angular Material: Using multiple filters and filter values simultaneously

Looking to implement dual filters for a table of objects, one being text-based and the other checkbox-based. The text filter works fine, but struggling with the checkbox filter labeled "Level 1", "Level 2", etc. Ideally, when a checkbox is checked, it shou ...

What steps do I need to take in order to ensure that each webpage displays unique thumbnails?

As a newcomer to website development, I recently looked into implementing open graph on my site. However, I ran into an issue where I could only set one thumbnail for the entire website. This posed a problem as I wanted each navigation menu tab (Home, Abou ...

Leveraging Angular Observables for seamless data sharing across components

As I embark on developing my very first Angular app, I have encountered a challenge with filtering a list of book objects based on their gender attribute. The issue lies in sharing data between components – specifically the filteredData variable and the ...

Using Typescript: accessing all properties from a specified type while excluding one

Currently working in React, I am interested in extending my type from another, with the exception of some props. This is how I want to approach it : import React from 'react'; import { withTheme } from 'styled-components'; import SvgBa ...

Playing around with Segment Analytics testing using Jest in TypeScript

I've been struggling to write a unit test that verifies if the .track method of Analytics is being called. Despite my efforts, the test keeps failing, even though invoking the function through http does trigger the call. I'm unsure if I've i ...

Sending an event from a child component to another using parent component in Angular

My form consists of two parts: a fixed part with the Save Button and a modular part on top without a submit button. I have my own save button for performing multiple tasks before submitting the form, including emitting an Event to inform another component ...

Iterate through an array containing objects that may have optional properties, ensuring to loop through the entire

I need help iterating through an array of objects with a specific interface structure: export interface Incident { ID: string; userName1?: string; userName2?: string; userPhoneNumber?: string; crashSeverity: number; crashTime: number; } Here ...

Following the build in Angular, it only displays the index.html file and a blank screen

According to the information on Angular's official website, running the "ng build" command should generate files in the dist folder ready for hosting. However, after running this command, the index.html file is empty except for the page title. When yo ...

What are the best practices for utilizing Vue.js slot components and managing interactions between parent and child components?

Recently, I've been exploring the slot component feature of Vue.js with the aim of understanding how to manipulate component information using slots. I decided to create a simple code snippet in order to grasp the concept of slot components better. Ho ...