I have several classes that I would like to include in a module, so I can then just import the module, as it was a different package, and use those classes from it. Here's a small example:
human.ts (my class file)
export class Human {
private numOfLegs: Number;
constructor() {
this.numOfLegs = 2;
}
}
test.module.ts (my module file)
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Human } from './human';
@NgModule({
imports: [CommonModule],
declarations: [
Human
],
providers: [],
exports: [Human]
})
export class TestModule {}
How do I instantiate the Human class in a component? I've tried both:
import { TestModule } from './test.module';
and
import { Human } from './test.module';
But if I do new Human()
I still get cannot find name Human
Angular modules and ES6 / TypeScript / Node modules are different. Angular modules are a collection of Components, Services and Directives; whereas the ES6 modules comprise of classes in most cases.
If you want to reuse your NgModule which is dependent on other non-Angular classes you can export them as ES6 modules and use them elsewhere. Have a file like export.ts or index.ts and place the following export statements there -
Now, when you want to use the NgModule somewhere, you import it with a command like the following -