Search code examples
angulardeprecatedangular2-directivesangular-componentsangular-rc5

Nesting components in Angular4 (RC5)


Getting into Angular and watching an outdated tutorial which is in fact for Angular2 (y, I know).

Angular4:

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ AppComponent , MyChildComponent ],
  bootstrap: [ AppComponent ]
})

Seems that this is how you nest components now but isn't there a way to do it how it was done (or similarly) in Angular 2? As in you could import it in the now-deprecated 'directives' property DIRECTLY IN YOUR ROOT COMPONENT (found this really convenient for fast development).

Angular2:

@Component({
   selector: 'app-root',
   directives: [MyChildComponent]
   template: '<div><ChildComponent></ChildComponent></div>'
})
export class AppComponent {}

Edit: Here's the MyChildComponent declaration (still part of Angular2):

@Component({
   selector: 'ChildComponent',
   template: '<h2>Child component</h2>'
})
export class MyChildComponent {}

Note: Omitted the import declarations


Solution

  • At some point (I lost track of the different versions popping up daily a long time ago) they made the switch to module-based design and essentially did away with the directives overnight.

    In order to use your components anywhere, you just need the declarations: [...] part in the module populated with your components in that module.

    After that, you don't need the directives portion in the components at all.

    In short:

    • Any components listed in the declarations section of a module will make those components available to all other components of that module.
    • Any components listed in the exports section of a module will make those components available to any other module that imports that module.