Dynamically incorporating validation to an ngModel input

Utilizing NgForm, I dynamically added a validator to the input field.

In my first example, everything works perfectly when I use the button setValidation to validate the input. However, in the second example where I add formGroup, I encounter an error when clicking the button setValidation:

Cannot read property 'setValidators' of null

@ViewChild('f') myForm: NgForm;
coumNameModel;

setValidation() {
  this.myForm.form.get('coumnName').setValidators([Validators.required, Validators.pattern("^[0-9]*$"), Validators.minLength(2), Validators.maxLength(2)]);
  this.myForm.form.get('coumnName').updateValueAndValidity();
}

First Example

<form #f="ngForm">
    <input type="text" [(ngModel)]="coumnNameModel" name="coumnName" #coumnName="ngModel">
</form>
<p *ngIf="!myForm.form.get('coumnName')?.valid">
    <i class="icons icon-cancel color-error"></i>
    <small class="color-error">Invalid</small>
</p>
<button (click)="setValidation()">Set Validation</button>

Second Example

<form [formGroup]="generalInformationForm" #f="ngForm">
    <input type="text" [(ngModel)]="coumnNameModel" name="coumnName" #coumnName="ngModel" gDefaultControl
        [ngModelOptions]="{standalone: true}">
</form>
<p *ngIf="!myForm.form.get('coumnName')?.valid">
    <i class="icons icon-cancel color-error"></i>
    <small class="color-error">Invalid</small>
</p>
<button (click)="setValidation()">Set Validation</button>

Answer №1

According to the official Angular documentation, the ngForm directive is explicitly initialized when there is no formGroup or ngNoForm present.

**Selectors**
   form:not([ngNoForm]):not([formGroup])
   ng-form
   [ngForm]

In the second example provided, a reactive form is used. To access information about a specific control, the get method must be utilized as shown below:

setValidation() {
  this.generalInformationForm.get('professionType').setValidators([Validators.required, Validators.pattern("^[0-9]*$"), Validators.minLength(2), Validators.maxLength(2)]);
  this.generalInformationForm.get('professionType').updateValueAndValidity();
}

Answer №2

The reason for the issue is that you have applied both formGroup and ngForm to the same form, which is not recommended.

I suggest sticking with one approach. In this case, I recommend using reactive forms with formGroup.

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

Experiencing a console error which reads: "SyntaxError: Missing ) after argument list."

While working on configuring a new React CSR app and incorporating some boilerplate libraries, I encountered an error in the console: Uncaught SyntaxError: missing ) after argument list (at @emotion_react_macro.js?v=30f6ea37:29894:134) I am hesitant to ma ...

Mysterious issue arises during deployment of Typescript-React application on Heroku

I am working on a TypeScript-React application generated using create-react-app. Deploying it to Heroku is proving to be a challenge as the process fails with an error message during installation and build: remote: Creating an optimized production b ...

Verify if an object property is called with the toHaveBeenCalledWith() function in Jasmine

Recently started incorporating Jasmine into my workflow and I am trying to verify if my method was called with an object that includes a MyProperty property. Currently, my setup looks like this: expect(service['method']).toHaveBeenCalledWith(jasm ...

The specified property 'XYZ' is not found in the type 'Readonly<{ children?: ReactNode; }> & Readonly<{}>'

Whenever I try to access .props in RecipeList.js and Recipe.js, a syntax error occurs. Below is the code snippet for Recipe.js: import React, {Component} from 'react'; import "./Recipe.css"; class Recipe extends Component { // pr ...

Expected single URL matching error in HttpTestingController

While testing my http service class and attempting to test the request, I encountered the following error: Expected one matching request for criteria "Match URL: https://beneficios/api/v1/processobeneficio/1111111111111/timeline", found none. I'm puz ...

Exploring NextJS with Typescript to utilize the getStaticProps method

I'm currently enrolled in a NextJS course and I am interested in using Typescript. While browsing through a GitHub discussion forum, I came across an issue that I don't quite understand. The first function provided below seems to be throwing an e ...

Encountering an error in Jest with TypeScript (Backend - Node/Express) that reads "Cannot use import statement outside a module

Currently, I am in the process of developing Jest tests for a Node/Express TypeScript backend. Recently, I came across the concept of global test setup which I am integrating to streamline the usage of variables and function calls that are repeated in all ...

Using GSAP in an Ionic application

What is the best way to add the GSAP library to an Ionic project? Simply running npm install gsap doesn't seem to work when I try to import it using: import { TweenMax, TimelineMax} from "gsap"; I am currently using TypeScript. Thank you. ...

"Exploring the process of passing an observable to map in RxJS

Being new to Angular and RxJS, I am currently working on a pipe function that utilizes several operators. One of the operators includes a 'map' with a ternary condition that can return either an empty array or another observable obtained from an ...

What is the most effective way to move specific data from one page to another in Angular/Typescript?

Welcome to my Main Page! https://i.stack.imgur.com/m9ASF.png This is where I want to start my journey. https://i.stack.imgur.com/E8pAW.png My goal is to click the Last 1 Day button to redirect to another page with the date filter and ItemId values already ...

Unable to bring in the directive from the Angular library

I've created this custom Directive within my library: @Directive({ selector: '[layoutHeaderTitle]', standalone: true }) export class HeaderDirective { constructor( readonly tpl: TemplateRef<any>, private re ...

Error occurs when attempting to instantiate a class with parameters that do not match any available constructor signatures

I am attempting to encapsulate each instance of router.navigateByUrl within a class function, with the intention of calling that function in the appropriate context. However, I am encountering an error that states 'Supplied parameters do not match any ...

Using Formik: When the initial value is changed, the props.value will be updated

After the initial props are updated, it is important to also update the values in the forms accordingly. export default withFormik({ mapPropsToValues: (props: Props) => { return ( { id: props.initialData.id, ...

What is the best way to determine the specific type of a value that is part of a union type?

Utilizing @azure/msal-react and @azure/msal-browser for implementing authentication in a React project with Typescript. The issue arises when TypeScript identifies event.payload as type EventPayload, but does not allow checking the exact type (e.g. Authen ...

What is the best way to include a new property to an existing interface and then export the updated interface in Typescript?

Can you provide guidance on creating a new interface - UIInterface that combines SummaryInterface with additional properties? For example: import { SummaryInterface } from 'x-api'; // summaryInterface includes 20+ predefined properties generated ...

What is the best way to utilize angular2 components based on their name using ngFor?

Check out the components I've created: app-widget-resume app-widget-my-courses-learner app-widget-my-courses-teacher app-widget-my-calendar app-widget-virtual-classes I want to populate my dashboard component, called my-dashboard, by util ...

Acquiring the url identifier along with parameters using the ActivatedRoute in Angular 2

I am attempting to retrieve a UUID from the URL (which is in the format of where uuid goes) and then utilize that UUID for an HTTP GET request. Currently, my app.component.ts appears as follows: private cardUuid: string; constructor(private service: App ...

Axios mandating the use of the "any" type for response type requirements

Currently, I am facing an issue while trying to retrieve data using Axios in my TypeScript React project. I have set the response type in axios to match CartItemType, however, Axios is enforcing the response type to be of CartItemType and any, which is cau ...

What is the best way to extract a property if it may be undefined?

Can anyone help with this TypeScript error I'm encountering during build time? Any suggestions would be appreciated. Error Message: TypeError: Cannot destructure property 'site' of '(intermediate value)' as it is undefined. export ...

Utilize the power of relative import by including the complete filename

When working on my TypeScript project, I have noticed that to import ./foo/index.ts, there are four different ways to do it: import Foo from './foo' // ❌ import Foo from './foo/index' // ❌ import Foo from './foo/i ...