Cannot use *ngFor in library

Viewed 9631

I have created an Angular library using:

  1. ng new my-workspace --create-application=false
  2. cd my-workspace
  3. ng generate library my-lib

The library works. However when I modify the template to use *ngFor as follows:

template:

<div *ngFor="let item of items">
  my-lib works!
</div>

I get an error:

No directive is matched on attribute ngFor

I have had no success with various suggestions found so far. If you know how to get a new clean library configured to use directives such as *ngFor I would greatly appreciate your advice. I have created the library with both Angular 8 and 9 with the result being the same.

Kind regards

Sean

4 Answers

Please import CommonModule inside your custom module. After that include it inside the imports array.

import {CommonModule} from '@angular/common';

imports: [
  CommonModule
]

Thank you all for your suggestions. I now have code that compiles and runs fine. However I am still getting errors in the IDE (Webstorm). The solution was to import CommonModule and then ignore the errors... I will follow up with JetBrains re possible Webstorm issue.

The solution from JetBrains to remove the errors was to change "peerDependencies" to "devDependencies" in the library's package.json file, then run npm install. This worked fine.

Can always switch to ng-template

<ng-template ngFor let-item [ngForOf]="items" let-i="index">
  my-lib works!
</ng-template>

You have issues with your Angular-CLI which is not properly installed. Even out of curiosity, I have followed the exact steps told by you in your question and found out that even if you will resolve this error by yourself, you will again receive trail of errors. So, its your CLI which is causing the issue. Try uninstalling Angular-CLI first and follow below steps

npm uninstall -g angular-cli
npm cache clean
npm cache verify or npm cache verify --force

And than re-install

npm install -g @angular/cli@latest
Related