Search code examples
angularangular-aottree-shaking

Is it possible to import a component without a module


I am wanting to import a component into another component in Angular 4.4.6. This may end up being just a theoretical answer, which is fine. Just figured I would reach out here to see if anyone is doing this. I typically would just create a module for the component etc. etc., but I am really trying to cut out any extra files - trying to avoid file smell.

I have no real code to share, although I am picturing something like this:

@Component({
     selector:'someSelector',
     template:`<html>some html</html>`,
     providers: [someService],
     declarations: [someComponent]  //wanting to do this but I know I can't
})

I do this already bring in outside components in a few places throughout the app, like parent/children communication with @ViewChild() so I get that. Just wondering if this is even possible without making the component I need access to in HTML globally available or if I have to create a module and import it like normal. Thanks!!


Solution

  • Till to Angular 2 RC5, you could add components into the another components directives property.

    Starting from Angular 2 RC5, components can be imported only in the modules. I think you will not use below versions of Angular, so you must to import them into the modules.

    Looking into the Documentation you can see that there are no declarations in the Component decorator

    @Component({ 
      changeDetection?: ChangeDetectionStrategy
      viewProviders?: Provider[]
      moduleId?: string
      templateUrl?: string
      template?: string
      styleUrls?: string[]
      styles?: string[]
      animations?: any[]
      encapsulation?: ViewEncapsulation
      interpolation?: [string, string]
      entryComponents?: Array<Type<any> | any[]>
      preserveWhitespaces?: boolean
      // inherited from core/Directive
      selector?: string
      inputs?: string[]
      outputs?: string[]
      host?: {...}
      providers?: Provider[]
      exportAs?: string
      queries?: {...}
    })