填寫這份《一分鐘調查》,幫我們(開發組)做得更好!去填寫Home

共享特性模組

Sharing modules

建立共享模組能讓你更好地組織和梳理程式碼。你可以把常用的指令、管道和元件放進一個模組中,然後在應用中其它需要這些的地方匯入該模組。

Creating shared modules allows you to organize and streamline your code. You can put commonly used directives, pipes, and components into one module and then import just that module wherever you need it in other parts of your app.

想象某個應用有下列模組:

Consider the following module from an imaginary app:

      
      import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { CustomerComponent } from './customer.component';
import { NewItemDirective } from './new-item.directive';
import { OrdersPipe } from './orders.pipe';

@NgModule({
 imports:      [ CommonModule ],
 declarations: [ CustomerComponent, NewItemDirective, OrdersPipe ],
 exports:      [ CustomerComponent, NewItemDirective, OrdersPipe,
                 CommonModule, FormsModule ]
})
export class SharedModule { }
    

請注意以下幾點:

Note the following:

  • 它匯入了 CommonModule,因為該模組需要一些常用指令。

    It imports the CommonModule because the module's component needs common directives.

  • 它宣告並匯出了一些工具性的管道、指令和元件類別。

    It declares and exports the utility pipe, directive, and component classes.

  • 它重新匯出了 CommonModuleFormsModule

    It re-exports the CommonModule and FormsModule.

透過重新匯出 CommonModuleFormsModule,任何匯入了這個 SharedModule 的其它模組,就都可以訪問來自 CommonModuleNgIfNgFor 等指令了,也可以繫結到來自 FormsModule 中的 [(ngModel)] 的屬性了。

By re-exporting CommonModule and FormsModule, any other module that imports this SharedModule, gets access to directives like NgIf and NgFor from CommonModule and can bind to component properties with [(ngModel)], a directive in the FormsModule.

即使 SharedModule 中宣告的元件沒有繫結過 [(ngModel)],而且 SharedModule 也不需要匯入 FormsModuleSharedModule 仍然可以匯出 FormsModule,而不必把它列在 imports 中。 這種方式下,你可以讓其它模組也能訪問 FormsModule,而不用直接在自己的 @NgModule 裝飾器中匯入它。

Even though the components declared by SharedModule might not bind with [(ngModel)] and there may be no need for SharedModule to import FormsModule, SharedModule can still export FormsModule without listing it among its imports. This way, you can give other modules access to FormsModule without having to import it directly into the @NgModule decorator.

關於 NgModule 的更多知識

More on NgModules

你可能還對下列內容感興趣:

You may also be interested in the following: