syy
syy

Reputation: 807

Angular import * into module declaration

I have a file that has all my components like this:

components.ts

export { ComponentA } from '../some/path/a.component';
export { ComponentB } from '../some/path/b.component';
export { ComponentC } from '../some/path/c.component';
// ... more here

In my module file, I have this:

components.module.ts

import { ComponentA } from '../some/path/components';
import { ComponentB } from '../some/path/components';
import { ComponentC } from '../some/path/components';
// ... more here

@NgModule({
    declarations: [ComponentA, ComponentB, ComponentC]
})
export class ComponentsModule { }

Is there a way I can just do import * as Components from '../some/path/components' and just put that in the declarations array? I have a lot of components and the list can become pretty big. In addition, every time I add a new component, I have to update both files when it would be better if I could just add it to the components.ts file as an export and the import * would take care of any new components in the module.

If someone knows, it would be greatly appreciated. Or should I even be doing it this way? If not, what would be a good practice?

I tried doing this but it returns a list of constructors for all the components and when I try to build it, Angular complains it can't determine the module for each component.

import * as exports from '../some/path/components';
const Components: any[] = Object.keys(exports).map(key => exports[key]);

...
delcarations: [Components]
...

Upvotes: 0

Views: 506

Answers (1)

Karsten
Karsten

Reputation: 389

Try to spread the Array into the declarations:

declarations: [...Components]

(instead Object.keys and then map, you could also simply use Object.values)

Upvotes: 1

Related Questions