[英]How to import component into another root component in Angular 2
我試圖從一個文件導入組件另一個根組件文件。 它給出了錯誤..
zone.js:484未處理的Promise拒絕:模板解析錯誤:'courses'不是已知元素:1。如果'courses'是Angular組件,則驗證它是否是此模塊的一部分。 2.如果“courses”是Web組件,則將“CUSTOM_ELEMENTS_SCHEMA”添加到此組件的“@NgModule.schema”以禁止顯示此消息。 (”
我的第一個Angular 2 App
[錯誤 - >]“):AppComponent @ 0:31;區域:;任務:Promise.then;值:錯誤:模板解析錯誤:(...)錯誤:模板解析錯誤:'courses'不是已知元素:
我的app.component.ts就像[根組件文件]
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 { }
和我的courses.component.ts是;
import { Component } from '@angular/core';
@Component({
selector: 'courses',
template: '<h1>courses</h1>'
})
export class CoursesComponent { }
從app.component中的courses.component.ts文件導入課程組件時,我無法在@Component{}
內聲明指令
directives:[CoursesComponent]
給我錯誤
請告知解決方案。
您應該使用declarations array(meta property) of @NgModule
聲明它,如下所示( RC5 and later
),
import {CoursesComponent} from './courses.component';
@NgModule({
imports: [ BrowserModule],
declarations: [ AppComponent,CoursesComponent], //<----here
providers: [],
bootstrap: [ AppComponent ]
})
對於Angular RC5和RC6,您必須在模塊元數據裝飾器的declarations
鍵中聲明組件,因此在主模塊declarations
添加CoursesComponent
, 如下所示,並從AppComponent
元數據中刪除directives
。
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 { }
角度RC5和RC6
如果您在Jasmine測試中遇到上述錯誤,則很可能是因為您必須在TestBed.configureTestingModule({})
聲明不可TestBed.configureTestingModule({})
組件。
TestBed為單元測試配置和初始化環境,並提供在單元測試中模擬/創建/注入組件和服務的方法。
如果在執行單元測試之前未聲明組件,Angular將不知道模板文件中的<courses></courses>
。
這是一個例子:
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();
});
});
上面的答案簡單來說,你必須在@NgModule
下注冊
declarations: [
AppComponent, YourNewComponentHere
]
app.module.ts
不要忘記import
該組件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.