如何将组件导入到 Angular 2 中的另一个根组件中 [英] How to import component into another root component in Angular 2
问题描述
我正在尝试从一个文件中导入另一个根组件文件中的组件.它给出的错误为..
I am trying to import component from one file another root component file. it give error as ..
zone.js:484 未处理的承诺拒绝:模板解析错误:课程"不是已知元素:1. 如果课程"是一个 Angular 组件,则验证它是否是该模块的一部分.2. 如果'courses' 是一个Web 组件,则将CUSTOM_ELEMENTS_SCHEMA"添加到该组件的'@NgModule.schema' 以抑制此消息.("
我的第一个 Angular 2 应用程序
[错误 ->]"): AppComponent@0:31 ;区域: ;任务:Promise.then;值:错误:模板解析错误:(…) 错误:模板解析错误:课程"不是已知元素: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:
我的 app.component.ts 就像 [根组件文件]
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 { }
我的courses.component.ts是;
and my courses.component.ts be ;
import { Component } from '@angular/core';
@Component({
selector: 'courses',
template: '<h1>courses</h1>'
})
export class CoursesComponent { }
从 app.component 中的 course.component.ts 文件导入课程组件时,我无法在 @Component{}
while importing courses component from courses.component.ts file inside app.component i am not able declare directive inside @Component{}
directives:[CoursesComponent]
给我错误
请提出解决方案.
推荐答案
你应该用@NgModule的declarations array(meta property)
声明它,如下所示(<代码>RC5 及更高版本),
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 ]
})
这篇关于如何将组件导入到 Angular 2 中的另一个根组件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!