前言
組件是Angular中很重要的一部分,下面這篇文章就來給大家介紹關(guān)于Angular入口組件(entry component)與聲明式組件的區(qū)別,Angular的聲明式組件和入口組件的區(qū)別體現(xiàn)在兩者的加載方式不同。
聲明式組件是通過組件聲明的selector加載
入口組件(entry component)是通過組件的類型動態(tài)加載
聲明式組件
聲明式組件會在模板里通過組件聲明的selector加載組件。
示例
@Component({ selector: 'a-cmp', template: ` <p>這是A組件</p> ` }) export class AComponent {}
@Component({ selector: 'b-cmp', template: ` <p>在B組件里內(nèi)嵌A組件:</p> <a-cmp></a-cmp> ` }) export class BComponent {}
在BComponent的模板里,使用selector<a-cmp></a-cmp>
聲明加載AComponent。
入口組件(entry component)
入口組件是通過指定的組件類加載組件。
主要分為三類:
在@NgModule.bootstrap
里聲明的啟動組件,如AppComponent。
在路由配置里引用的組件
其他通過編程使用組件類型加載的動態(tài)組件
啟動組件
app.component.ts
@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent{}
app.module.ts
@NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, BrowserAnimationsModule, AppRoutingModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
在bootstrap里聲明的AppComponent為啟動組件。雖然我們會在index.html里使用組件的selector<app-root></app-root>
的位置,但是Angular并不是根據(jù)此selector來加載AppComponent。這是容易讓人誤解的地方。因為index.html不屬于任何組件模板,Angular需要通過編程使用bootstrap里聲明的AppComponent類型加載組件,而不是使用selector。
由于Angular動態(tài)加載AppComponent,所有AppComponent是一個入口組件。
路由配置引用的組件
@Component({ selector: 'app-nav', template: ` <nav> <a routerLink="/home" routerLinkActive #rla="routerLinkActive" selected="#rla.isActive">首頁</a> <a routerLink="/users" routerLinkActive #rla="routerLinkActive" selected="#rla.isActive">用戶</a> </nav> <router-outlet></router-outlet> ` }) export class NavComponent {}
我們需要配置一個路由
const routes: Routes = [ { path: "home", component: HomeComponent }, { path: "user", component: UserComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
Angular根據(jù)配置的路由,根據(jù)路由指定的組件類來加載組件,而不是通過組件的selector加載。
配置入口組件
在Angular里,對于入庫組件需要在@NgModule.entryComponents
里配置。
由于啟動組件和路由配置里引用的組件都為入口組件,Angular會在編譯時自動把這兩種組件添加到@NgModule.entryComponents
里。對于我們自己編寫的動態(tài)組件需要手動添加到@NgModule.entryComponents
里。
@NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, BrowserAnimationsModule, AppRoutingModule ], providers: [], entryComponents:[DialogComponent], declarations:[] bootstrap: [AppComponent] }) export class AppModule { }
相信看了本文案例你已經(jīng)掌握了方法,更多精彩請關(guān)注Gxl網(wǎng)其它相關(guān)文章!
推薦閱讀:
node+token做出用戶驗證
如何操作Angular項目內(nèi)使用scss
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com