天天看點

angular2中自定義子產品的構造與使用

angular中内置子產品有:

核心子產品:@angular/core

通用子產品:@angular/common

表單子產品:@angular/forms

網絡子產品:@angular/http

……

angular中的自定義子產品

前提:當我們項目比較小的時候可以不用自定義子產品。但是當我們項目非常龐大的時候把所有的元件都挂載到根子產品裡面不是特别合适。是以這個時候我們就可以自定義子產品來組織我們的項目。并且通過路由的懶加載來加載Angular自定義子產品,也可以手動引入

一、手動引入建立的子產品(不推薦)

建立檔案

// 1、建立user子產品 modules是自己命名的,user是建立的子產品
ng g module modules/user
// 2、建立user裡的元件 components是放元件的檔案夾自己命名,home是元件
ng g component modules/user/components/home
ng g component modules/user/components/chrees
// 3、建立user的跟元件
ng g component modules/user
// 4、建立服務 第二個service是檔案夾名,bigser是服務名
ng g service modules/user/service/bigser
           

上述指令執行後的結果如下:

angular2中自定義子產品的構造與使用

引入

引入到app根子產品中

1、先在

user.module.ts

子產品裡暴露元件

angular2中自定義子產品的構造與使用

2、在

app.module.ts

裡引入

import { UserModule } from './modules/user/user.module';
@NgModule({
……
  imports: [
	……
    UserModule,
  ],
……
})
           

3、

app.component.html

根子產品使用

第一種使用方法,在

app.component.html

裡調用user及user的子元件

angular2中自定義子產品的構造與使用

結果:

angular2中自定義子產品的構造與使用

第二種方法,在

app.component.html

裡隻調用user

angular2中自定義子產品的構造與使用

user.components.html

裡調用user的子元件

angular2中自定義子產品的構造與使用

兩者結果一樣

注意:不同之處在于

user.module.ts

暴露的子產品。使用第一種方式時,必須把user的子元件也暴露。使用第二種方式時,隻需暴露user根子產品就行,也就是

UserComponent

二、懶加載引入建立的子產品(推薦)

1、建立檔案

// 1、建立content、produce子產品  --routing是建立路由的意思
ng g module modules/content --routing
ng g module modules/product --routing
// 2、建立content、produce子產品裡的元件
ng g component modules/content/components/cone
ng g component modules/content/components/ctwo
ng g component modules/product/components/pone
ng g component modules/product/components/ptwo
// 3、建立content、produce子產品的跟元件
ng g component modules/content
ng g component modules/product
           

上述指令執行後的結果如下:

angular2中自定義子產品的構造與使用

2、引入

import { ProductModule } from './modules/product/product.module';
import { ContentModule } from './modules/content/content.module';
@NgModule({
 ……
  imports: [
 	……
    ProductModule,
    ContentModule
  ],
……
})
           

3、配置路由

配置product、content的路由

angular2中自定義子產品的構造與使用
angular2中自定義子產品的構造與使用

這兩個子產品配置的路由不一樣,具體原因看下面的細講,此處先跳過

配置app的路由

angular2中自定義子產品的構造與使用

使用:

angular2中自定義子產品的構造與使用
angular2中自定義子產品的構造與使用

結果

angular2中自定義子產品的構造與使用
angular2中自定義子產品的構造與使用

兩個路由配置不一樣的解釋

1、同級别的配置子產品及子產品子元件

有跳過的作用,同級别嘛,顯示子元件,父元件的内容就隐藏了,同時,注意位址欄輸入

angular2中自定義子產品的構造與使用
angular2中自定義子產品的構造與使用

2、父子級别的配置子產品及子產品子元件

顯示子元件的同時,父元件的内容不隐藏,注意位址欄顯示

angular2中自定義子產品的構造與使用
angular2中自定義子產品的構造與使用
angular2中自定義子產品的構造與使用