'FormsModule Not Working Properly in Different Module Than App Module

i have FormsModule present in SharedModule..

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';

@NgModule({
  declarations: [],
  imports: [
    CommonModule
  ],
  exports : [
    CommonModule,
    FormsModule,
    BrowserModule
  ]
})
export class SharedModuleModule { }

and this sharedModule is imported in every module. But Forms module doesnt work.

it gives error -

No directive found with exportAs 'ngForm'.

But when i import this module(where sharedModule is imported) in my app.module.ts, FormsModule start working.

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

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

import { LoginModule } from './login/login.module'

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


Solution 1:[1]

You are exporting modules that you have not imported in your shared module,

Amend your shared module to

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';

@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    FormsModule,
    BrowserModule
  ],
  exports : [
    CommonModule,
    FormsModule,
    BrowserModule
  ]
})
export class SharedModuleModule { }

Solution 2:[2]

In my case:

  1. Use angular 13.2.0
  2. Use nx workspace
  3. Setting path in tsconfig.json
  4. Export NgForm from SharedModule (Not import in SharedModule, just export)

Then I have the same issue.
If I import error module (LoginModule) in app.module.ts (just import in typescript file), can solve the problem too.

I Found the problem is import statement in my router.module.ts

  1. Import by relative path will cause "ngForm not found"
    ex: import {LoginComponent} from "./modules/login/components/login/login.component";

  2. Import by relative path with index.ts still cause "ngForm not found"
    ex: import {LoginComponent} from "./modules/login";

  3. Import by tsconfig path still cause "ngForm not found"
    ex: import {LoginComponent} from "@cms-ng-modules/login/components/login/login.component";

  4. Import by tsconfig path with index.ts will... solve the problem
    ex: import {LoginComponent} from "@cms-ng-modules/login";

I solve the problem, but I don't know why...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Owen Kelvin
Solution 2 markhuang1994