You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular项目NG8001错误:'app-bmi-calculator'未知元素如何解决?

问题解决步骤

你的问题源于独立组件(standalone component)的使用方式错误,同时存在文件路径拼写问题,具体修正如下:

1. 修正组件模板与样式路径

bmi.component.ts中templateUrl和styleUrls的路径缺少开头的./,导致Angular无法定位文件,修正后代码:

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

@Component({
    selector: 'app-bmi-calculator', 
    standalone : true,
    templateUrl: './bmi.component.html', // 补全路径前缀
    styleUrls: [
        './bmi.component.css' // 补全路径前缀
    ]
})
export class bmiComponent{
    weight : number;
    height : number;

    constructor(){
        this.weight = 50;
        this.height = 1.6;
    }
}

2. 移除NgModule中对独立组件的声明

独立组件不需要在AppModule的declarations数组中注册,否则会触发冲突,修改app.module.ts:

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

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
    // 移除 bmiComponent 声明,独立组件无需在此注册
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

3. 在宿主组件中导入独立组件

要在AppComponent中使用独立组件,需在其@Component元数据的imports数组中导入bmiComponent,修改app.component.ts:

import { Component } from '@angular/core';
import { bmiComponent } from './bmi/bmi.component';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  imports: [bmiComponent] // 导入独立组件
})
export class AppComponent {
  title = 'your-app-title';
}

额外建议:Angular组件类名规范为大驼峰命名,建议将bmiComponent改为BmiComponent,保持代码风格统一。

内容的提问来源于stack exchange,提问作者Leichtos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 12:03:16