首页 > 解决方案 > 手动创建的 Angular 组件未显示

问题描述

我刚刚开始学习 Angular,并且正在尝试练习如何不仅使用 CLI,还手动创建组件。我在一个文件夹中创建了我的组件以及 HTML、CSS 和 .TS 文件。下面是我的代码:

HTML 和 CSS

    <h1>WARNING ALERT: IT IS RAINING OUTSIDE!!</h1> //in HTML file
    h1
    {
      color:red; //in CSS file
    }

.TS 文件:

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

    @Component({
        selector: 'app-warning',
        templateUrl: 'src/app/warningalert/warningalert.component.html'
    })
    
    export class WarningAlertComponent{
    
    }

我像这样在app.component.html中添加了元素: <app-warning></app-warning>并将其导入到app.module.ts文件中,如下所示:

import { AppComponent } from './app.component';
import {WarningAlertComponent} from 'src/app/warningalert/warningalert.component'; //Warning Component

@NgModule({
  declarations: [
    AppComponent,
    WarningAlertComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})

除了这个新创建的组件之外,我的 app.component.html 文件中的所有其他内容都会显示出来,我无法弄清楚我缺少什么。我阅读了一些 SO 帖子并像他们说的那样导入了组件,但我仍然无法弄清楚为什么该组件没有出现。这是我得到的错误:

Error: ./src/app/warningalert/warningalert.component.ts
Module not found: Error: Can't resolve './src/app/warningalert/warningalert.component.html' in '/Users/Desktop/basics-assignment-1-start/src/app/warningalert'

标签: angulartypescriptimportangular-components

解决方案


尝试将您的 templateUrl 更新为相对路径:

    @Component({
        selector: 'app-warning',
        templateUrl: './warningalert.component.html'
    })

推荐阅读