您好,登錄后才能下訂單哦!
小編給大家分享一下Angular入口組件與聲明式組件的區(qū)別有哪些,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
前言
組件是Angular中很重要的一部分,下面這篇文章就來給大家介紹關(guān)于Angular入口組件(entry component)與聲明式組件的區(qū)別,Angular的聲明式組件和入口組件的區(qū)別體現(xiàn)在兩者的加載方式不同。
聲明式組件是通過組件聲明的selector加載
入口組件(entry component)是通過組件的類型動(dòng)態(tài)加載
聲明式組件
聲明式組件會(huì)在模板里通過組件聲明的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
里聲明的啟動(dòng)組件,如AppComponent。
在路由配置里引用的組件
其他通過編程使用組件類型加載的動(dòng)態(tài)組件
啟動(dòng)組件
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為啟動(dòng)組件。雖然我們會(huì)在index.html里使用組件的selector<app-root></app-root>
的位置,但是Angular并不是根據(jù)此selector來加載AppComponent。這是容易讓人誤解的地方。因?yàn)閕ndex.html不屬于任何組件模板,Angular需要通過編程使用bootstrap里聲明的AppComponent類型加載組件,而不是使用selector。
由于Angular動(dòng)態(tài)加載AppComponent,所有AppComponent是一個(gè)入口組件。
路由配置引用的組件
@Component({ selector: 'app-nav', template: ` <nav> <a routerLink="/home" routerLinkActive #rla="routerLinkActive" selected="#rla.isActive">首頁(yè)</a> <a routerLink="/users" routerLinkActive #rla="routerLinkActive" selected="#rla.isActive">用戶</a> </nav> <router-outlet></router-outlet> ` }) export class NavComponent {}
我們需要配置一個(gè)路由
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里,對(duì)于入庫(kù)組件需要在@NgModule.entryComponents
里配置。
由于啟動(dòng)組件和路由配置里引用的組件都為入口組件,Angular會(huì)在編譯時(shí)自動(dòng)把這兩種組件添加到@NgModule.entryComponents
里。對(duì)于我們自己編寫的動(dòng)態(tài)組件需要手動(dòng)添加到@NgModule.entryComponents
里。
@NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, BrowserAnimationsModule, AppRoutingModule ], providers: [], entryComponents:[DialogComponent], declarations:[] bootstrap: [AppComponent] }) export class AppModule { }
以上是“Angular入口組件與聲明式組件的區(qū)別有哪些”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。