小編給大家分享一下Angular入口組件與聲明式組件的區別有哪些,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
前言
組件是Angular中很重要的一部分,下面這篇文章就來給大家介紹關于Angular入口組件(entry component)與聲明式組件的區別,Angular的聲明式組件和入口組件的區別體現在兩者的加載方式不同。
聲明式組件是通過組件聲明的selector加載
入口組件(entry component)是通過組件的類型動態加載
聲明式組件
聲明式組件會在模板里通過組件聲明的selector加載組件。
示例
@Component({ selector: 'a-cmp', template: ` <p>這是A組件</p> ` }) export class AComponent {}
@Component({ selector: 'b-cmp', template: ` <p>在B組件里內嵌A組件:</p> <a-cmp></a-cmp> ` }) export class BComponent {}
在BComponent的模板里,使用selector<a-cmp></a-cmp>
聲明加載AComponent。
入口組件(entry component)
入口組件是通過指定的組件類加載組件。
主要分為三類:
在@NgModule.bootstrap
里聲明的啟動組件,如AppComponent。
在路由配置里引用的組件
其他通過編程使用組件類型加載的動態組件
啟動組件
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并不是根據此selector來加載AppComponent。這是容易讓人誤解的地方。因為index.html不屬于任何組件模板,Angular需要通過編程使用bootstrap里聲明的AppComponent類型加載組件,而不是使用selector。
由于Angular動態加載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根據配置的路由,根據路由指定的組件類來加載組件,而不是通過組件的selector加載。
配置入口組件
在Angular里,對于入庫組件需要在@NgModule.entryComponents
里配置。
由于啟動組件和路由配置里引用的組件都為入口組件,Angular會在編譯時自動把這兩種組件添加到@NgModule.entryComponents
里。對于我們自己編寫的動態組件需要手動添加到@NgModule.entryComponents
里。
@NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, BrowserAnimationsModule, AppRoutingModule ], providers: [], entryComponents:[DialogComponent], declarations:[] bootstrap: [AppComponent] }) export class AppModule { }
以上是“Angular入口組件與聲明式組件的區別有哪些”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。