26

I am trying to use ngModel to do data binding, however, I get an error ngForm not found. I have already included formsmodule in app.module.ts as you can see below. The error disappears when i remove #grantAccessForm= "ngForm" but when i do this and input data in input field and submit, my page refreshes and the refreshed page has params in the url, like this: "http://localhost:8100/signup?name=a&userName=a&email=a@email.com&password=aa&confirm=aa"

I want to be able to do something in the onSubmit() function without the page being refreshed, can someone explain to me what #grantAccessForm= "ngForm" this means and why am i getting this error.

app-routing.module.ts

import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';
import { LoginPageComponent } from './login/login-page/login-page.component';
import { SignUpPageComponent } from './login/sign-up-page/sign-up-page.component';

const routes: Routes = [
  {
    path: 'home',
    loadChildren: () => import('./home/home.module').then( m => m.HomePageModule)
  },
  {
    path: '',
    component: LoginPageComponent
  },
  {
    path: 'login',
    component: LoginPageComponent,

    //()=> import('./login/login-page/login-page.component').then(m=> m.LoginPageComponent)
  },
  {
    path: 'signup',
    component: SignUpPageComponent
  }
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
  ],
  exports: [RouterModule]
})
export class AppRoutingModule { }

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { FormsModule } from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule,
    FormsModule,
    IonicModule.forRoot(), 
    AppRoutingModule, 
    ReactiveFormsModule
  ],
  exports:[],

  providers: [
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

sign-up-page.component.html

</ion-content>
  <form #grantAccessForm= "ngForm" (ngSubmit)="onSubmit(grantAccessForm)">
    <ion-grid>
      <ion-row justify-content-center>
        <ion-col align-self-center size-md="6" size-lg="5" size-xs="12">
          <div  class="centerText">
            <h3>Create your account!</h3>
          </div>
          <div padding>

            <ion-item>
              <ion-input  name="name" type="text" placeholder="Name" [(ngMode)]="dataModel.name"></ion-input>
            </ion-item>

            <ion-item>
              <ion-input  name="userName" type="text" placeholder="Username"  [(ngModel)]="dataModel.username"></ion-input>
            </ion-item>

            <ion-item>
              <ion-input name="email" type="email" placeholder="your@email.com"  [(ngModel)]="dataModel.email"></ion-input>
            </ion-item>

            <ion-item>
              <ion-input name="password" type="password" placeholder="Password"  [(ngModel)]="dataModel.password"></ion-input>
            </ion-item>

            <ion-item>
              <ion-input name="confirm" type="password" placeholder="Password again"  [(ngModel)]="dataModel.passwordAgain"></ion-input>
            </ion-item>
          </div>
          <div padding>
            <ion-button  size="large" type="submit" expand="block" >Register</ion-button>
          </div>
        </ion-col>
      </ion-row>
    </ion-grid>
  </form>
</ion-content>

sign-up-page.component.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms'; 
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@Component({
  selector: 'app-sign-up-page',
  templateUrl: './sign-up-page.component.html',
  styleUrls: ['./sign-up-page.component.scss'],
})
export class SignUpPageComponent implements OnInit { 

// Import ViewChild
@ViewChild('grantAccessForm', {static: false}) grantAccessForm: NgForm;
dataModel: any = {}; // Your data model


  constructor() { }

  ngOnInit() {}

  onSubmit(form) {
    console.log(form);
    
  }

}
Ashim
  • 877
  • 2
  • 12
  • 22
  • This also happens when you apply the directive to an input or another form control. If input, try `ngModel` instead. – Addis Apr 18 '22 at 03:19

19 Answers19

14

i had the same issue so you need to add you singUpComponent in the app.module.ts

11

I faced the similar issue, in my case I was trying to open that component from a ModalController.

The solution is in app.module.ts under imports you need to add FormsModule & you need to add the component in declarations array.

The below mentioned app.module.ts should work

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import {SignUpPageComponent} from './sign-up-page.component';
import { AppRoutingModule } from './app-routing.module';
import { FormsModule } from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  declarations: [AppComponent,SignUpPageComponent],
  entryComponents: [],
  imports: [
    BrowserModule,
    FormsModule,
    IonicModule.forRoot(), 
    AppRoutingModule, 
    ReactiveFormsModule
  ],
  exports:[],

  providers: [
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}
10

I am facing this issue while using Reactive Forms in the component. I found this error in unit test case execution.

Simple solution is add ReactiveFormsModule in the imports section.

beforeEach(async () => {
  await TestBed.configureTestingModule({
    declarations: [ YourComponent ],
    imports: [AppRoutingModule,ReactiveFormsModule],
    providers: [ AuthService],
  })
  .compileComponents();
});

This will solve your issue.

Tejashree
  • 750
  • 12
  • 14
4

Add FormsModule in app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
2

Same Issue I have faced for below step it's work for me

  • import FormsModule for app module and working current module from both places'
  • import ngForm in you ts file then do the below steps
  1. terminate console
  2. run npm install
  3. run server again
vicky raj
  • 59
  • 1
1

I terminated the server. executed the npm install command and tried once again. Got the issue resolved.

1

FormsModule is imported in your app.module.ts file, it is ok.

After putting the "ngForm" directive:

https://angular.io/api/forms/NgForm#listening-for-form-submission

According to the sample template in the link, you have to put "ngModel" directive with the template reference variable (#var) into all form elements.

I tried and worked for me.

  <form #grantAccessForm= "ngForm" (ngSubmit)="onSubmit(grantAccessForm)">
    <ion-grid>
      <ion-row justify-content-center>
        <ion-col align-self-center size-md="6" size-lg="5" size-xs="12">
          <div  class="centerText">
            <h3>Create your account!</h3>
          </div>
          <div padding>

            <ion-item>
              <ion-input  name="name" type="text" placeholder="Name" [(ngMode)]="dataModel.name" #inputName="ngModel"></ion-input>
            </ion-item>

            <ion-item>
              <ion-input  name="userName" type="text" placeholder="Username"  [(ngModel)]="dataModel.username" #userName="ngModel"></ion-input>
            </ion-item>

            <ion-item>
              <ion-input name="email" type="email" placeholder="your@email.com"  [(ngModel)]="dataModel.email" #inputEmail="ngModel"></ion-input>
            </ion-item>

            <ion-item>
              <ion-input name="password" type="password" placeholder="Password"  [(ngModel)]="dataModel.password" #inputPassword="ngModel"></ion-input>
            </ion-item>

            <ion-item>
              <ion-input name="confirm" type="password" placeholder="Password again"  [(ngModel)]="dataModel.passwordAgain" #inputPassword2="ngModel"></ion-input>
            </ion-item>
          </div>
          <div padding>
            <ion-button  size="large" type="submit" expand="block" >Register</ion-button>
          </div>
        </ion-col>
      </ion-row>
    </ion-grid>
  </form>
cowboycb
  • 539
  • 5
  • 11
1

well i got the same error and manage to fix it. So first if you separated the modules or created an extra module or in app.modulets.ts file you need to add your component to declarations and import imports. Exp: on createdExtra.module.ts or app.modulets.ts do

@NgModule({
  declarations: [...
                  componetWithNgForm,
                 ...
                 ],
  imports: [
    ...
    FormsModule
  ]

Hope i helped.

Fe3back
  • 924
  • 7
  • 15
1

I faced the same issue. I resolved it by adding the component on which I was using ngForm to the declarations list of app.module.ts.

Edor Linus
  • 826
  • 8
  • 9
0
  1. here you miss spelled ngmodel for dataModel.name.
  2. Change ion-button html given in answer.

sign-up-page.component.html

<ion-content padding>
  <h2>Welcome to Ionic!</h2>
  <form #grantAccessForm="ngForm" (ngSubmit)="onSubmit(grantAccessForm)">
    <ion-grid>
      <ion-row justify-content-center>
        <ion-col align-self-center size-md="6" size-lg="5" size-xs="12">
          <div  class="centerText">
            <h3>Create your account!</h3>
          </div>
          <div padding>

            <ion-item>
              **<!-- Here you miss spelled ngModel -->**
              <ion-input  name="name" type="text" placeholder="Name" [(ngModel)]="dataModel.name"></ion-input> 

            </ion-item>

            <ion-item>
              <ion-input  name="userName" type="text" placeholder="Username"  [(ngModel)]="dataModel.username"></ion-input>
            </ion-item>

            <ion-item>
              <ion-input name="email" type="email" placeholder="your@email.com"  [(ngModel)]="dataModel.email"></ion-input>
            </ion-item>

            <ion-item>
              <ion-input name="password" type="password" placeholder="Password"  [(ngModel)]="dataModel.password"></ion-input>
            </ion-item>

            <ion-item>
              <ion-input name="confirm" type="password" placeholder="Password again"  [(ngModel)]="dataModel.passwordAgain"></ion-input>
            </ion-item>
          </div>
          <div padding> 
            **<!-- Here change button html -->**
            <button ion-button  size="large" type="submit" expand="block" >Register</button>
          </div>
        </ion-col>
      </ion-row>
    </ion-grid>
  </form>
</ion-content>
Santosh Shinde
  • 1,206
  • 10
  • 16
0

After some trial and error, my problem was the the module that holds my form component was lazy loaded.

tal
  • 525
  • 2
  • 8
  • 26
0

I faced a similar issue in a component that is part of a lazy loaded module. Though I imported FormsModule and ReactiveFormsModule into my module and added routing to that component, I forgot to add the component in the declarations. Adding the component there fixed it

Niranjan
  • 77
  • 9
0

Just in case someone faces similar problem... Getting the error Error: Export of name 'ngForm' not found even if FormsModule is imported correctly in your own module

This can happen as well if your form declaration is on a; say; a div instead of a form element.

Prefer

    <form #myForm="ngForm"></form>

than

    <div #myForm="ngForm"></div>
Royalsmed
  • 212
  • 1
  • 4
  • 16
0

I had same issue resolved by the following First way.

I was call one Common component(Popup-component) from two different modules like one is patient module and another is doctor module , And i was import the common "Popup-component" in patient module but was not import in doctor module.

So that was the problem when i call the common "Popup-component" from doctor module it generate error, because it was not import in doctor module

ERROR Error: Export of name 'ngForm' not found

So first you need to check you have imported the component in that module from where you calling it. ..........................

Second way

i just import the common "Popup-component" in main app.module.ts and then remove from patient and doctor module .

It also worked for me I think the second way is best.

try this i hope your problem will be solved

Siraj Ali
  • 526
  • 6
  • 13
0

For me terminating the server and restarting it solved the issue.

Its funny when sometimes Angular also behaves like Microsoft -- don't do anything, just restart and things start working...

Lakshman Pilaka
  • 1,803
  • 2
  • 24
  • 48
0

In the following code, this problem is related to the "role" attribute:

<!-- Wrong -->
<form role="form" (ngSubmit)="save(userForm.value)" userForm="ngForm"></form>   
<!-- Correct -->
<form (ngSubmit)="save(userForm.value)" #userForm="ngForm"></form>
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
  • 3
    Can you provide more information on what your code does? Also providing information such as what the differences are between the two blocks of code will result in a better quality answer. – Tyler2P Oct 12 '21 at 16:34
0

WORKING SOLUTION ON THIS ISSUE:

I was having the same problem, to fix this issue you can import formsModule to app.module.ts or directly on the component's .module.ts file.

The most important thing that nobody say's is YOU MUST NEED to import the component you created on app.module.ts file if you don't do then it will won't work and your ngForm won't be detected

So make sure you imported your component Module to app.module.ts. This way I could solve the issues. and cost me a few hours for that investigation, which nobody said.

Code Cooker
  • 881
  • 14
  • 19
0

If you have this error with unit testing: import the FormsModule into your component.spec.ts:

import { FormsModule } from '@angular/forms';

 beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [YourComponent],
      imports: [FormsModule],
    }).compileComponents();
  });
kingabdr
  • 588
  • 5
  • 12
-1

Hard reset to the application url resolved my error

Sameer
  • 11
  • 3
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 15 '22 at 13:34