How to import component into another root component in Angular 2

Vishu picture Vishu · Sep 9, 2016 · Viewed 127.8k times · Source

I am trying to import component from one file another root component file. it give error as ..

zone.js:484 Unhandled Promise rejection: Template parse errors: 'courses' is not a known element: 1. If 'courses' is an Angular component, then verify that it is part of this module. 2. If 'courses' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schema' of this component to suppress this message. ("

My First Angular 2 App

[ERROR ->]"): AppComponent@0:31 ; Zone: ; Task: Promise.then ; Value: Error: Template parse errors:(…) Error: Template parse errors: 'courses' is not a known element:

My app.component.ts be like [root component file]

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

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

export class AppComponent { }

and my courses.component.ts be ;

import { Component } from '@angular/core';
@Component({
  selector: 'courses',
  template: '<h1>courses</h1>'
})
export class CoursesComponent { }

while importing courses component from courses.component.ts file inside app.component i am not able declare directive inside @Component{}

directives:[CoursesComponent] giving error to me

Please advise solution over it.

Answer

micronyks picture micronyks · Sep 9, 2016

You should declare it with declarations array(meta property) of @NgModule as shown below (RC5 and later),

import {CoursesComponent} from './courses.component';

@NgModule({
  imports:      [ BrowserModule],
  declarations: [ AppComponent,CoursesComponent],  //<----here
  providers:    [],      
  bootstrap:    [ AppComponent ]
})