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

Angular CLI创建组件报错:选择器“src/app-{module name}”无效

解决Angular CLI创建组件时的“选择器无效”错误

常见原因与修复步骤

1. 组件名称违反选择器规范

Angular组件选择器必须遵循HTML自定义元素规则:

  • 必须包含至少一个连字符(例如app-user-list,不能是userlist)
  • 不能以数字开头
  • 不能包含大写字母(CLI默认会自动转成小写加连字符,但手动指定时需注意)

如果手动指定--selector参数,检查是否符合规则。示例:
错误写法:

ng g c UserProfile --module app

正确写法(让CLI自动生成合规选择器):

ng g c user-profile --module app

或手动指定合规选择器:

ng g c user-profile --module app --selector app-user-profile

2. 命令参数顺序错误

ng g c的正确语法是先指定组件名称,再附加参数。若把--module放在组件名称前,会导致CLI解析错误,误将模块名识别为组件名称,进而生成无效选择器。

错误写法:

ng g c --module app user-profile

正确写法:

ng g c user-profile --module app

3. 模块路径/名称错误

确认--module后的值是正确的模块名称(比如app对应app.module.ts)或完整相对路径,不存在的模块会触发解析异常,间接导致选择器错误:

ng g c shared/user-profile --module app/shared/shared.module.ts

4. CLI缓存或版本问题

尝试清理CLI缓存:

npm cache clean --force

若问题依旧,可更新到同大版本的最新补丁版:

npm install @angular/cli@15.2.x --save-dev

5. 项目配置冲突

检查angular.json中的schematics配置,若存在自定义组件选择器模板,可能和你输入的组件名称规则冲突,需调整配置或组件命名方式。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 06:52:09