Andrei Rosu
Andrei Rosu

Reputation: 1387

Angular2 reference component inside another component

I am following an Angular2 tutorial and I have to reference an extra component to the main component. I want to insert the template from the "CoursesComponent" inside the < courses > tag of the main component. For this I am using "directives: []", but it's not working. I get the error: 'courses' is not a known element'. Is directives no longer used for this, and I should do it differently?

App.component.ts

import {Component} from '@angular/core';
import {CoursesComponent} from './courses.component'

@Component({
  selector: 'my-app',
  template: '<h1>My first Angular2 app</h1><courses></courses>',
  directives: [CoursesComponent]
})

export class AppComponent {}

Courses.component.ts

import {Component} from '@angular/core';

@Component({
    selector: 'courses',
    template: '<h2>Courses</h2>'
})

export class CoursesComponent {}

Upvotes: 1

Views: 2091

Answers (1)

micronyks
micronyks

Reputation: 55443

NOTE : IN RC6, you don't have to declare directives and pipes meta properties within @Component

As AppComponent uses CourseComponent, you have to declare CourseComponent in declaration metadata of @NgModule as shown below.

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent }  from './app.component';
import {CoursesComponent} from './courses.component'
@NgModule({
  imports:      [ BrowserModule],
  declarations: [ AppComponent,CoursesComponent],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

NOTE: Now, You have to remove directives metadata used within @Component.

import {Component} from '@angular/core';
import {CoursesComponent} from './courses.component'

@Component({
  selector: 'my-app',
  template: '<h1>My first Angular2 app</h1><courses></courses>',
  //directives: [CoursesComponent]        //<-----remove this from here
})

export class AppComponent {}

Upvotes: 2

Related Questions