Does @NgModules couples by declaring directives, s

2019-09-11 06:00发布

问题:

I just upgraded to angular2 RC5 and red this article about @NgModules.
https://angularjs.blogspot.de/2016/08/angular-2-rc5-ngmodules-lazy-loading.html

With @NgModules the components, directives, services etc. get declared on the modules root level. My thought on that was: Don't we try to decouple thinks and don't we try to archive building components who could be used even by it's own?

What about if I now have a component for example "NoteCard" which is used in a "container"-component "Notes".

NoteCard:

import {Component} from "@angular/core";

@Component({
    selector: 'note-card',
    styleUrls: ['app/ui/note-card/note-card.css'],
    templateUrl: 'app/ui/note-card/note-card.html'
})
export class NoteCard {}

Notes:

import {Component} from "@angular/core";
import {NoteCard, NoteCreator} from "../../ui";
import {NotesService} from "../../services";

@Component({
    selector: 'notes-container',
    directives: [
        NoteCard
    ],
    styleUrls: ['app/containers/notes/notes.css'],
    templateUrl: 'app/containers/notes/notes.html'
})
export class Notes {}

In RC4 we would just inject "NoteCard" into "Notes". By that we could use "NoteCard" by itself (Off course it has no dependencies) and "Notes" in combination with "NoteCard" because it's its own dependency.

With RC5 I have to inject "NoteCard" into the @NgModule root level. With that I always need an extra level and if it gets more complex it could be several levels above where the dependencies get injected.

Does it make sense to use more than one @NgModule in a project? In my case should every "container"-component be a @NgModule?

回答1:

Sure it makes sense to have multiple modules! Otherwise you dont use the benefits of this new feature.

Please read this article: https://angular.io/docs/ts/latest/guide/ngmodule.html

Its quite long, yes.. but there are many examples, code-snippets and plunkers.

In that live demo you will see the different modules and sometimes there is just one component inside, sometimes there are more. And you decide which components are visible (exported) to the outside of your module.