【问题标题】:Can't use component in Angular 8无法在 Angular 8 中使用组件
【发布时间】:2019-12-16 00:47:28
【问题描述】:

我正在学习 Angular 8,即使在其他问题上搜索了一个小时后,我也无法解决这个问题。解决方案似乎在我的眼皮底下,但我看不到。我不断收到此错误:

'app-green' 不是已知元素: 1. 如果“app-green”是一个 Angular 组件,那么验证它是这个模块的一部分。 2. 如果“app-green”是一个 Web 组件,则将“CUSTOM_ELEMENTS_SCHEMA”添加到该组件的“@NgModule.schemas”以禁止显示此消息。

这是我的 app.module.ts 代码

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {FormsModule} from '@angular/forms';

import { AppComponent } from './app.component';
import { ServerComponent } from './servers/server.component';
import { SubServerComponent } from './sub-server/sub-server.component';
import { GreenComponent } from './green/green.component';



@NgModule({
  declarations: [
    AppComponent,
    ServerComponent,
    SubServerComponent,
    GreenComponent,


  ],
  imports: [
    BrowserModule, 
    FormsModule, 

  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

这是组件代码:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-green',
  templateUrl: './green.component.html',
  styleUrls: ['./green.component.css']
})
export class GreenComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

任何帮助将不胜感激。

【问题讨论】:

  • 在您的module.ts 中添加import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';,然后添加@NgModule({ ...schemas: [ CUSTOM_ELEMENTS_SCHEMA ] }) -- 了解更多信息:stackoverflow.com/a/39553713/8757883
  • 你想在哪里插入这个组件?是在AppModule 还是您创建了其他模块?
  • 显然 Visual Studio Code 搞糊涂了。一个程序员朋友告诉我用Cmd+Shit+P重新加载,然后选择Developer:reload window,错误就消失了。
  • 我偶尔会遇到这个问题。终止开发服务器并重新启动。
  • 我强烈建议不要将 CUSTOM_ELEMENTS_SCHEMA 用于除浅层单元测试之外的任何事情;隐藏错误不是最好的解决方案。

标签: angular


【解决方案1】:

您还必须在 AppComponent 中导入 GreenComponent,而您显然没有这样做。 正如人们所相信的那样,在 AppModule 中导入 GreenComponent 是不够的。

import { Component } from '@angular/core';
import { GreenComponent } from './green/green.component';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],  

})
export class AppComponent  {
  ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-21
    • 2020-03-16
    • 2020-01-11
    • 2020-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-21
    相关资源
    最近更新 更多