Search code examples
angularwebsingle-page-applicationangular2-components

nested Components in angular2


I'm going to upgrade my knowledge of angular2 from version Rc5 to 2.2. I have problem with directive property that had been deprecated since i upgraded my packages.I know it moves to imports property on NgModule decorator but it called Shared Components but when i have very large number of components that i have to move from directives on every component to starting point of my app at NgModule and therefor all of my Components have to Load at start,i don't know if there is a way to bring back directives to Components to lazy load Components inside other Components.


Solution

  • As my friend told,nesting components in angular has been deprecated and instead Module loading comes inside. here's how I implement that in my way: first,I found that we can lazy load a module with new router,so i Modularize areas of my app and change my main module

    import { NgModule }      from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import {homeComponent} from './appComponent/homeComponent.Component'
    import { AppComponent }  from './appComponent/app.component';
    import {RouterModule} from '@angular/router'
    
    @NgModule({
      imports:      [ BrowserModule,
        RouterModule.forRoot([
          { path: '', redirectTo: 'home', pathMatch: 'full' },
          { path: 'home', component: homeComponent },
          { path: 'lazy1', loadChildren: './dist/app/detailComponent/detailModule.Module#detailModule' }
    
        ], {})
      ],
      declarations: [ AppComponent,homeComponent ],
      bootstrap:    [ AppComponent ]
    })
    export class AppModule { }
    

    Last root route shows that how we can asign a Module instead of imported Component,and then we configure our child routes in second module and act like this:

    import { NgModule }      from '@angular/core';
    import { DetailComponent } from '../detailComponent/detail.component'
    import { RouterModule, Route, Router} from '@angular/router';
    
    @NgModule({
      imports:[ RouterModule.forChild([ {path: '', component: DetailComponent}])],
      declarations: [ DetailComponent ]
    })
    export class detailModule { }
    

    as this code shows we can configure our second level module to load its components and use it to reduce network load a little at first (using systemjs) and load it as user clicks the menu links. Note that we can continue nesting our modules in the second level module routing configuration

    Also we can load a Module and its Components with builtin angular class named SystemJsNgModuleLoader