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

Angular 12执行ng lint报The selector should be used as an element错误如何修复

报错原因

你当前的MenuItemComponent使用了属性选择器[app-menu-item],不符合Angular ESLint@angular-eslint/component-selector规则默认要求的「组件使用元素选择器」规范,所以触发报错。

以下是两种符合你要求的修复方案:

方案1:完全遵循规范修改为元素选择器

不需要关闭规则,修改代码适配规范即可。

步骤1:修改组件选择器

打开menu-item.component.ts,调整@Component装饰器中的selector配置:

@Component({
  // 把原来的 selector: '[app-menu-item]' 改为
  selector: 'app-menu-item',
  // 其他配置保持不变
})

步骤2:调整组件模板

把模板最外层的<ng-container>替换为<li>标签,同时修改模板内递归调用的子组件写法:

template: `
  <li>
    <!-- 原有模板的a、ul等内容全部保持不变 -->
    <a ...></a>
    <ul ...>
      <ng-template ngFor let-child let-i="index" [ngForOf]="item.items">
        <!-- 把原来的 <li app-menu-item ...></li> 改为 -->
        <app-menu-item
          [item]="child"
          [index]="i"
          [parentKey]="key"
          [class]="child.badgeClass"
        ></app-menu-item>
      </ng-template>
    </ul>
  </li>
`,

步骤3:修改组件调用代码

把原来的属性调用方式改为元素调用:

<!-- 原来的写法 -->
<!-- <li app-menu-item *ngFor="let item of model; let i = index" [item]="item" [index]="i" [root]="true"></li> -->
<!-- 改为 -->
<app-menu-item *ngFor="let item of model; let i = index" [item]="item" [index]="i" [root]="true"></app-menu-item>

适配说明

你之前写的@HostBinding类绑定会自动作用在app-menu-item元素上,只需要给app-menu-item加一行样式即可和原有li的表现完全一致:

app-menu-item {
  display: list-item;
}

方案2:仅针对当前组件禁用规则(无业务代码改动)

如果你因为HTML语义要求必须使用li+属性选择器的结构,可以不用修改任何业务逻辑,仅在当前组件文件顶部加一行注释,单独禁用该规则,不会影响项目其他文件的校验:

/* eslint-disable @angular-eslint/component-selector */
import { Component, Input, OnInit, ChangeDetectorRef, OnDestroy, HostBinding } from '@angular/core';
// 后续所有代码保持原样即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 17:18:03