Angular 5 个组件在选择器中需要一个 `-` 吗?

Do Angular 5 components need a `-` in the selector?

我正在查看此 Angular 5 forms youtube tutorial,Sebastian 最初将表单选择器命名为 app-form01,但他删除了 app- 部分。 IIUC 自定义元素应该有 -。这是放松了吗?

- 根本不需要。它被认为是良好做法,因为它符合自定义元素要求。 除此之外,无论是否使用 -,组件的行为都将完全相同,您还可以使用大小写混合的名称。

另见

During the kebab-case removal we kept element selectors dasherized because of custom element spec.

Component name remains dash-cased because a dash is required by the custom element spec, which we use for guidance since even after making Angular templates case-sensitive the templates remain valid html5 fragments (although with higher fidelity due to case-sensitivity that only our html parser can see).

Very few people know about the custom element spec and the guarantees the dash gives us, so I think that it would be better to enforce that all directive/component element selectors have at least a single dash in it. There should be a way to opt out via a flag in the Component/Directive metadata, but it shouldn't be on by default.

If someone is unfamiliar with the custom element spec, the benefits of adding a dash to the element name are:

  • the element becomes a custom element - the type of the DOM node is HTMLElement instead of HTMLUnknownElement
  • in case we need it, we can benefit from the :unresolved psedo-class by registering a fake element via document.registerElement
  • the spec guarantees that browsers will not introduce native elements with a dash in the name, meaning that apps won't break in the future should browsers natively implement an element that matches an Angular Component selector (e.g. )

More info about custom elements.

你的标签可以没有 - 分隔词,Angular 不会知道你的词被加入了,它只是它的另一个标识符:

<app-my-tag> -> <appmytag>

此外,您可以完全省略整个前缀:

<app-my-tag> -> <mytag>

但是,不使用 - 分隔符会使您的标签更难阅读,并且不为您的自定义标签使用前缀会增加名称冲突的可能性。