6

In the Angular2 tutorial a detail component is introduced by adding it to the @NgModule.

Instead, I would like to add it by the outer component (AppComponent) somehow importing it, so that only the outer component refers to the inner component.

I can't figure out how to do it. Old examples refer to the directives property, but directives no longer exist in the type ComponentMetadtaType. So this does not work

import { HeroDetailComponent } from './hero-detail.component';

@Component({
    selector: 'my-app',
    [..]
    directives: [HeroDetailComponent]
})

2 Answers 2

4

You have to add directives and components to declarations: [] of a module.
If you want to only one component to be able to use a component, create a module that consists only of these two components.

@NgModule({
  imports: [BrowserModule],
  declarations: [AppComponent, FooComponent, BarDirective],
  ...
})
Sign up to request clarification or add additional context in comments.

3 Comments

You may be right, but you're essentially saying that what I want to do is not possible to do in the way I want to?
I explained what "somehow importing it" can look like. In Angular2 final you are required to use modules and it's the only way to make one component, directive or pipe known to another component.
@KlasMellbourn That's not exactly what he is saying. It's true that you cannot declare a component in another component. So the declaration should be moved to an outer module, which will still be fine because other modules/components will not know about this outer module, it's exactly as your old outer component declaration.
0

You should declare it with declarations metadata as shown below,

import { HeroDetailComponent } from './hero-detail.component';
@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ AppComponent,HeroDetailComponent],   //<----here
  providers:    [],
  bootstrap:    [ AppComponent ]
})

1 Comment

That is not they way I want to do it. I'd like to declaratively import the inner component in the outer component that is using the inner component. The @NgModule declaration does not make clear what is using what. But maybe what I want is impossible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.