user3230660
user3230660

Reputation:

When is a directive required in component metadata in Angular2?

In the angular tutorial found here: https://angular.io/docs/ts/latest/tutorial/toh-pt3.html

the HeroDetailComponent is added as a directive to app.component.ts:

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

The tutorial says: "A browser ignores HTML tags and attributes that it doesn't recognize. So does Angular... We tell Angular about it (the HeroDetailComponent) by listing it in the metadata directives array."

However in the working example found here: https://github.com/DeborahK/Angular2-GettingStarted (see the APM - Final Updated project)

app.component.ts loads a component named ProductDetailComponent yet has no directive for it:

@Component({
    selector: 'pm-app',
    //...
    directives: [ROUTER_DIRECTIVES],    
})

Why is the second example able to load ProductDetailComponent without a ProductDetailComponent directive?

Upvotes: 3

Views: 1789

Answers (1)

Picci
Picci

Reputation: 17762

From what I can see, AppComponent imports ProductDetailComponent but uses it via <router-outlet> since ProductDetailComponent is defined in @Routes.

This means that <router-outlet> just defines where the components will be shown when you decide to navigate to them (which in this case happens executing the code <a [routerLink]="['/product', product.productId]"> present in product-list.component.html).

ProductListComponent does not define any selector and therefore could not be referenced within the template of any other component.

A component needs to define in its directives the Components/Directive which are referenced within its template via their selectors.

I hope this helps

Upvotes: 1

Related Questions