How to import component into another root component in Angular 2
above answers In simple words,
you have to register under @NgModule
's
declarations: [
AppComponent, YourNewComponentHere
]
of app.module.ts
do not forget to import
that component.
For Angular RC5 and RC6 you have to declare component in the module metadata decorator's declarations
key, so add CoursesComponent
in your main module declarations
as below and remove directives
from AppComponent
metadata.
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 { }
Angular RC5 & RC6
If you are getting the above mentioned error in your Jasmine tests, it is most likely because you have to declare the unrenderable component in your TestBed.configureTestingModule({})
.
The TestBed configures and initializes an environment for unit testing and provides methods for mocking/creating/injecting components and services in unit tests.
If you don't declare the component before your unit tests are executed, Angular will not know what <courses></courses>
is in your template file.
Here is an example:
import {async, ComponentFixture, TestBed} from "@angular/core/testing";
import {AppComponent} from "../app.component";
import {CoursesComponent} from './courses.component';
describe('CoursesComponent', () => {
let component: CoursesComponent;
let fixture: ComponentFixture<CoursesComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent,
CoursesComponent
],
imports: [
BrowserModule
// If you have any other imports add them here
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(CoursesComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
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 ]
})