欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Angular入口組件(entry component)與聲明式組件的區(qū)別詳解

 更新時(shí)間:2018年04月09日 10:31:39   作者:ngoing  
這篇文章主要給大家介紹了關(guān)于Angular入口組件(entry component)與聲明式組件的區(qū)別的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。

前言

組件是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">首頁</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里,對于入庫組件需要在@NgModule.entryComponents里配置。

由于啟動(dòng)組件和路由配置里引用的組件都為入口組件,Angular會(huì)在編譯時(shí)自動(dòng)把這兩種組件添加到@NgModule.entryComponents里。對于我們自己編寫的動(dòng)態(tài)組件需要手動(dòng)添加到@NgModule.entryComponents里。

@NgModule({ declarations: [  AppComponent ], imports: [  BrowserModule,  BrowserAnimationsModule,  AppRoutingModule ], providers: [], entryComponents:[DialogComponent], declarations:[] bootstrap: [AppComponent] }) export class AppModule { }

總結(jié)

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。

相關(guān)文章

最新評(píng)論