我试图在其他模块中使用我在AppModule中创建的组件。我得到以下错误:
Uncaught (in promise):错误:模板解析错误
'contacts-box'不是已知元素:
如果'contacts-box'是一个Angular组件,那么验证它是否是这个模块的一部分。
如果'contacts-box'是一个Web组件,那么在'@NgModule '中添加'CUSTOM_ELEMENTS_SCHEMA'。模式来抑制此消息。
我的项目结构很简单:
我将页面保存在pages目录中,其中每个页面保存在不同的模块中(例如customers-module),每个模块都有多个组件(例如customers-list-component, customers-add-component等)。我想在这些组件中使用我的ContactBoxComponent(例如在customers-add-component内部)。
As you can see I created the contacts-box component inside the widgets directory so it's basically inside the AppModule. I added the ContactBoxComponent import to app.module.ts and put it in declarations list of AppModule. It didin't work so I googled my problem and added ContactBoxComponent to export list as well. Didn't help. I also tried putting ContactBoxComponent in CustomersAddComponent and then in another one (from different module) but I got an error saying there are multiple declarations.
我错过了什么?
这个复杂的框架快把我逼疯了。假设你在同一个模块的另一个组件部分的模板中定义了自定义组件,那么你不需要在模块中使用导出(例如app.module.ts)。你只需要在前面提到的模块的@NgModule指令中指定声明:
// app.module.ts
import { JsonInputComponent } from './json-input/json-input.component';
@NgModule({
declarations: [
AppComponent,
JsonInputComponent
],
...
你不需要将JsonInputComponent(在本例中)导入到AppComponent(在本例中)来使用AppComponent模板中的JsonInputComponent自定义组件。你只需要在自定义组件前加上两个组件都定义过的模块名(例如app):
<form [formGroup]="reactiveForm">
<app-json-input formControlName="result"></app-json-input>
</form>
注意app-json-input不是json-input!
演示在这里:https://github.com/lovefamilychildrenhappiness/AngularCustomComponentValidation
很多答案/注释提到了在其他模块中定义的组件,或者你必须在它/它们的包含模块中导入/声明组件(你想在另一个组件中使用)。
但在简单的情况下,当组件B和组件A都定义在同一个模块中时,你必须在包含组件的模块中声明两个组件,以便B看到A,而不仅仅是A。
例如,在my-module.module.ts中
import { AComponent } from "./A/A.component";
import { BComponent } from "./B/B.component";
@NgModule({
declarations: [
AComponent, // This is the one that we naturally think of adding ..
BComponent, // .. but forget this one and you get a "**'AComponent'**
// is not a known element" error.
],
})
我有一个类似的问题,但没有一个提到的解决方案工作。最后我意识到我有一个路由问题:
我想如果我在应用程序路由中指定我的组件。模块如下:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { MainComponent } from './pages/main/main.component';
const routes: Routes = [
{
path: '',
component: MainComponent
},
]
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
我将不必在我的AppModule中导入MainModule,这是错误的,因为这里只有组件被导入。MainModule中声明的任何其他组件将不可见,这将导致您所描述的错误消息。
解决方案1:
导入声明模块
解决方案2:
惰性加载组件,如下所示:
const routes: Routes = [
{
path: '', loadChildren: () => import('path_to_your_module').then(m => m.MainModule)},
}
这是可行的,因为整个模块都导入到这里。
我意识到你在你的例子中没有使用路由,只是把这个发布给其他可能使用路由的人,并无意中发现了这个问题。