The reason behind this error message "Error: ngModel cannot be used to register form controls with a parent formGroup directive" is due to the form validation

Greetings! I've encountered this issue

Error: ngModel cannot be used to register form controls with a parent formGroup directive

I'm attempting to implement basic validation for form inputs

Below is the snippet of my form

<form [formGroup]="formgroup">

   <ion-item>
        <ion-label floating>First Name</ion-label>
        <ion-input type="text" formControlName="firstname" [(ngModel)]= "userData.firstname" ></ion-input>
   </ion-item>

   <ion-item *ngIf="firstname.hasError('required') && firstname.touched">
        <p>*First Name Is Required</p>
    </ion-item>

    <ion-item>
        <ion-label floating>Last Name</ion-label>
        <ion-input type="text" formControlName="lastname" [(ngModel)]= "userData.lastname" ></ion-input>
    </ion-item>

   <ion-item *ngIf="lastname.hasError('required') && lastname.touched">
        <p>*First Name Is Required</p>
   </ion-item>  

</form>

And here's my controller implementation

import  {FormBuilder,FormGroup,Validators,AbstractControl,FormControl} from '@angular/forms'; 

    export class Form1Page {

      formgroup:FormGroup;
      firstname:AbstractControl;
      lastname:AbstractControl;

      userData = {"firstname":"", "lastname":""};  

      constructor(public navCtrl: NavController, public navParams: NavParams,public formBuilder:FormBuilder) {

        this.formgroup = formBuilder.group({
                 firstname:['',Validators.required,Validators.minLength(5)],
                 lastname:['',Validators.required,Validators.maxLength(15)]
        });

        this.firstname = this.formgroup.controls['firstname'];

        this.firstname = this.formgroup.controls['lastname'];

        this.userData.dateOfBirth = new Date().toISOString();
      }

}

If you have any suggestions on resolving these challenges, your assistance would be greatly appreciated

Thank you in advance!!!

Answer №1

You made a mistake in typing the controls. You assigned to the firstname twice, leaving your lastname uninitialized. Update the second assignment to be for the lastname.

Revise

this.firstname = this.formgroup.controls['firstname'];
this.firstname = this.formgroup.controls['lastname'];

to

this.firstname = this.formgroup.controls['firstname'];
this.lastname = this.formgroup.controls['lastname'];

Explore the Angular Reactive Forms documentation for more information.

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

Launching Angular 2 Application on Azure Cloud

I have recently been diving into the world of Angular 2 and Azure. Following the steps outlined in the Angular 2 Tutorial, I was able to successfully run my application locally without any issues. After deploying the app to Azure, I encountered a problem. ...

Informing ng2-bootstrap's Timepicker of the invalidation

I have integrated ng2-bootstrap's timepicker component into my project. To enhance user experience, I created a custom validation function that is triggered by the ngModelChange() event. However, the timepicker component also comes with its own built- ...

What is the best way to incorporate zone.js into an Angular 2 application?

I have chosen not to use webpack or browserify in my ASP.NET core & Angular2 application. Instead, I am utilizing systemjs to load modules. I am facing a dilemma regarding how to best handle the loading of zone.js within my app. Here are the different opti ...

Conversation with form component in angular2

I am currently using ng2-bootstrap-modal. For adding a sample form to the example Confirm Dialog, check out ng2-bootstrap-modal. To change the template: <div class="modal-dialog"> <div class="modal-content"> <form [formGroup]="login ...

The requested page for angular-in-memory-web-api could not be located within the Angular 4.2.2 CLI web-api functionality

Currently, I am delving into the Angular framework (specifically version 4.2.2) and going through the Tour of Heroes tutorial. As I progressed to the HTTP section, the tutorial introduced the use of angular-in-memory-web-api to simulate a web api server. ...

transform JSON structure into an array

Is it possible to convert an interface class and JSON file into a list or array in order to work on it? For example, extracting the Racename from each object in the JSON file and storing it in a list/array. Here is the interface structure: interface IRunn ...

Sometimes encounter undefined values after assigning them through the service

One of the challenges I am facing is handling public fields in my service: @Injectable() export class ShareDataService { // Some code public templateForCurrencyCOS; public templateForPercentCOS; public templateForCurrencyCOGS; public te ...

Angular refreshes outdated DOM element

Within my Angular (v9) application, I have a simple component. The main goal of this component is to display the current date and time when it is first shown, and then after a 2-second delay, enable a button. Here's the code snippet from app.component ...

Issue: The inject() function must be activated within an injection context, however, the origin cannot be located

While utilizing angularfire's authentication service for user registration and login in my application, I encountered an error when triggering the register or sign-in method: Error: inject() must be called from an injection context Despite attempting ...

Adding a new script child to a specific Angular component

Currently, I am including an external JavaScript source in my component using the following method: The Component TypeScript file this.script = this._renderer2.createElement('script'); this.script.type = 'text/javascript'; this.script. ...

Creating a Loading Sign with a Button Component in React

Request Description: In my form, I have a button that triggers a submission to the backend. While the request is processing, I want the button to display a loading indicator instead of the usual text. Once the request is complete, I need the form to disap ...

Manage interfaces and structures

I am looking to implement user roles in my application. Here is a snippet of the code I would like to use: export interface User{ name: string roles: Roles[] } interface Roles{ ADMIN: new Permissions(1,1,1,1,1), MOD: new Permissions(1,0,1,1,0,0), [. ...

I encountered an error when attempting to retrieve a JSON from a URL using a previously provided solution. What might be causing this issue?

Currently, I am facing an issue while trying to retrieve a JSON file for my memory card game. Even after following the solution provided in this question: How to get json file from HttpClient?, I encounter an error message that is quite confusing for me: h ...

Is there a way to specify this component without it being nested within the parent element?

So I have this component nested within another one const selectColumn = useMemo<ColumnDef<Person>[]>( () => [ { id: "select", header: ({ table }) => ( <IndeterminateCheckbox {.. ...

Array of options with specified data types in Props interface

Trying to implement options as props for styling a button component in Astro. Still learning TypeScript. Encountering the error message: Generic type 'Props<style>' requires 1 type argument(s). Below is the code snippet: --- import type { H ...

The preflight request for Ionic 7 fails the access control check, even though all origins, methods, and headers are permitted

Snippet; this.http.post(this.endpoint + "api/auth/signin", {"username": handle, "password": password}).subscribe(res => { // @ts-ignore if (res["status"] === "authorized") { loc ...

Ways to resolve: The JSX component does not contain any construction or call signatures

I've been grappling with a persistent issue regarding the creation of custom elements dynamically in React TypeScript. If you're curious, you can check out the question here. const generalButtons: MenuButton[] = [ { text: "New Cl ...

Tips for pulling out specific keys from a typed object using an index signature

TL;DR Query: How do I create a type converter in TypeScript that extracts the defined keys from objects typed with index signatures? I am looking to develop a type "converter" in TypeScript that takes a type A as input and outputs a new type B with keys ...

Simulate a complete class with its constructor, instance methods, and static functions

I have been searching for a comprehensive example that demonstrates how to properly mock all three elements (ClassA constructor, ClassA.func1 instance function, and ClassA.func2 static function) in my TypeScript project. In the code under test, I need to v ...

Tips for sending the current URL to a SignalR Hub in .NET Core while utilizing WebSockets

Currently, I am utilizing SignalR in a front-end Angular application paired with a back-end .NET Core. My goal is to transmit the current page URL from the client to the server when initiating a SignalR connection. Initially, my approach involved trying to ...