angular - 如果 '<x>' 是一个 Angular 组件,那么验证它是这个模块的一部分

标签 angular typescript

我在使用 Angular 的组件时遇到了问题。我的应用程序仅使用一个模块 (app.module)。我创建了一个名为“BooksComponent”的组件,其中包含用于 html 的选择器“app-books”。当我在 app.component 中使用它时,出现此错误:

'app-books' is not a known element: 1. If 'app-books' is an Angular component, then verify that it is part of this module. 2. If 'app-books' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

我的代码是这样的:

books.component.ts

import { Component, OnInit } from '@angular/core';
import { Book } from '../book';
import { BOOKS } from '../mock-books';


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

        books = BOOKS;
        selectedBook : Book;

  constructor() { }

  ngOnInit() {
  }

}

app.component.ts

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


@Component({
  selector: 'app-root',
  template: `<h1>{{title}}</h1>
            <app-books></app-books>`
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'BookShelf';
}

最后: 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 { BooksComponent } from './books/books.component';
import { BookDetailComponent } from './book-detail/book-detail.component';


@NgModule({
  declarations: [
    AppComponent,
    BooksComponent,
    BookDetailComponent,

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

我已经在应用程序模块中声明并导入了 BooksComponent,所以我不明白我缺少什么!请帮忙!

最佳答案

如果您在运行测试时遇到错误,这可能意味着规范需要了解新组件 BooksComponent

为了解决这个问题,请将以下内容添加到您的 app.component.spec.ts 文件中。

import { BooksComponent } from './books/books.component';

然后在 beforeEach() 方法的声明中,添加如下新组件:

beforeEach(async(() => {
  TestBed.configureTestingModule({
    declarations: [
      AppComponent, BooksComponent
    ],
  }).compileComponents();
}));

关于angular - 如果 '<x>' 是一个 Angular 组件,那么验证它是这个模块的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48489533/

相关文章:

node.js - 合并命名空间和变量的声明

javascript - 模板编译时出错 'SharedModule' 不支持表达式形式

angular - 如何编写模拟数据以从 Angular 服务中获取值(value)

unit-testing - 模拟 router.events.subscribe() Angular2

angular - angular4/typescript 中的 document.getElementById 替换?

d3.js - Angular2-Seed + Typings + D3 : Import error, 'Cannot find module ' d 3''

angular - 以编程方式打开 ng-bootstrap 模式

jquery - 类型 'ripples' 上不存在属性 'JQuery<HTMLElement>' 。 Angular 分量

angularjs - 在非 Angular 页面中散布 Angular 2 组件

angular - 如何从服务器响应 Angular 2 中读取内容配置 header