在 Angular 6
(6.0.7) 中,我试图通过 CLI 生成一个组件。我输入 ng g c t1-2-3-user
并收到错误消息 Selector (app-t1-2-3-user) is invalid。
这个名字中有什么本质上不允许的东西吗?我已经通过 ng g module t1-myModule
创建了一个名为 t1-myModule
的父模块,并且创建成功。在那个模块中,我试图生成这个组件。
我已经尝试创建一个不同的名称,例如 ng g c t1-testComponent
,它工作正常 - 因此 CLI 似乎没有被破坏。 Angular 不喜欢在我的设置中命名组件 t1-2-3-user
。
编辑: 经过进一步测试,Angular 似乎不喜欢破折号 -
之后的第一个字符是数字。可能与 JavaScript 变量中的限制类似。我假设因为它被编译成 JavaScript?谁能详细说明/确认此组件命名限制?
最佳答案
根据 W3C standards选择器应符合以下条件
In CSS, identifiers (including element names, classes, and IDs in selectors) can contain
- only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_);
- they cannot start with a digit, two hyphens, or a hyphen followed by a digit
- Identifiers can also contain escaped characters and any ISO 10646 character as a numeric code (see next item). For instance, the identifier "B&W?" may be written as "B\&W\?" or "B\26 W\3F".
因此 Angular 遵循 W3C 选择器名称约定。我预计会在某处的内部代码中看到类似的东西。在深入研究 CLI 代码后发现,angular 使用正则表达式 (/^[a-zA-Z][.0-9a-zA-Z]*(:?-[a-zA-Z][.0 -9a-zA-Z]*)*$/
) 在创建文件之前验证选择器
名称。
因此,在运行 ng generate component component-name
命令时,它会为 component
命令调用 @angular/schematics
并将组件名称参数传递给它。在使用指令集执行命令时,它会触发 below line验证选择器。
validateHtmlSelector(options.selector);
export const htmlSelectorRe = /^[a-zA-Z][.0-9a-zA-Z]*(:?-[a-zA-Z][.0-9a-zA-Z]*)*$/;
export function validateHtmlSelector(selector: string): void {
if (selector && !htmlSelectorRe.test(selector)) {
throw new SchematicsException(tags.oneLine`Selector (${selector})
is invalid.`);
}
}
关于Angular 组件命名限制 - 'selector [your component name] is invalid',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53231588/