3

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!!

BSchnitzel
  • 136
  • 2
  • 15

2 Answers2

2

Component declarations and providers were supported in Angular 2 RC4. Angular modules were introduced in RC5 and are supposed to fully replace this functionality in modules.

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.

In order to be unavailable globally, a component/directive should be specified in module declarations but not exports. Its selector will be compiled only in components/directives that belong to same module.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
1

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?: {...}
})
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112