I can't add new component with angular cli in asp.net core spas

Viewed 13302

I want to add a new component in asp.net core 2.0 SPAs with angular 4 with angular cli with this version:

@angular/cli: 1.4.2

node: 8.4.0

os: Linux x64

when I running this command ng g c vehicle-form on a directory of components got this error:

Error: Could not find an NgModule for the new component. Use the skip-import option to skip importing components in NgModule. Could not find an NgModule for the new component. Use the skip-import option to skip importing components in NgModule.

app.module.shared.ts

Also, I have 3 files for app.module.ts not one :\ :

app.module.browser.ts

app.module.shared.ts

app.module.server.ts

9 Answers

In my case problem was in e2e project. After I move my project from angular 4 to angular 6 a new angular config file was added "angular.json" instead "angular.conf.json". In a projects section appeared two project: One of them my "ng-app" and other "ng-app-e2e". When I try execute "ng g c" command i catch a same error. A cause was in root section of "ng-app-e2e". It had empty value. I set it into "e2e". Now all is ok! This occurs despite the fact that the default project set in "ng-app".

"projects": {
    "ng-app": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "app",
      ...
    },
    "ng-app-e2e": {
      "root": "e2e", <-- SALVATION
      "sourceRoot": "e2e",
      "projectType": "application",
      ...
    }
  },
  "defaultProject": "ng-app"  

In the case of an ASP Net Core Angular project, the app.module is split across 3 files as you've highlighted. The angular CLI has to decide where to add the reference to the component in the module, so you need to provide it with some help.

ng g c moduleName --module='app.module.browser.ts'

in .angular-cli.json in part "apps" replace "./src" to "src"

"apps": [ { "root": "src", "outDir": "dist",

I had the same problem while converting 5 to 6 version. I found the solution from github. when I removed e2e from sourceRoot It solved the problem.

This error will occur in case if app.module.ts file is not present. Please verify if the file is present and if it does not exist, create one manually.

1- Copy an angular.json from a default angular project into your asp.net mvc core project. 2- maybe needs to install npm install @angular/cli@latest --save-dev 3- open angular.json and change

 "root": "./ClientApp",
 "sourceRoot": "./ClientApp/src",

then you can use ng g c vehicle-form

Related