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

Angular中appMySortGrid指令绑定报错的排查与修复

Angular指令绑定NG8002错误的修复方案

错误根源分析

你遇到的NG8002: Can't bind to 'appMySortGrid' since it isn't a known property of 'div'错误,来自两处代码不匹配:

  1. 模板拼写错误
    指令的选择器是[appMySortGrid],但组件模板里写的是[appMnhSortGrid](My误写为Mnh),直接导致Angular无法识别该指令。

  2. 输入属性与绑定语法不匹配
    你试图通过[appMySortGrid]="inputArray"给指令传值,但指令中定义的输入属性是@Input() sortList: any;,两者名称不一致。Angular中,若要通过指令选择器绑定数据,需保证输入属性名称与选择器同名,或使用别名关联。


修复步骤

步骤1:修正模板拼写错误

将组件模板中的[appMnhSortGrid]改为[appMySortGrid],确保与指令选择器完全一致:

<div *ngFor="let inputObj of inputArray" [hidden]="isHidden(inputObj)" [appMySortGrid]="inputArray" draggable="true"> </div>

步骤2:匹配输入属性与绑定语法

有两种可选方案:

方案A:修改指令输入属性名称,与选择器同名

直接将指令的输入属性改为和选择器一致的名称,模板绑定即可直接生效:

import { Directive, HostListener, Input, ElementRef, Renderer2 } from '@angular/core';

@Directive({
    selector: '[appMySortGrid]'
})
export class MySortGridDirective {
    // 改为与选择器同名的输入属性
    @Input() appMySortGrid: any;
}
方案B:保留原输入属性,调整模板绑定方式

如果不想修改指令代码,可在模板中单独声明指令,并绑定到对应的输入属性:

<div *ngFor="let inputObj of inputArray" [hidden]="isHidden(inputObj)" appMySortGrid [sortList]="inputArray" draggable="true"> </div>

这里appMySortGrid作为指令的启用标识(无需方括号),[sortList]="inputArray"负责传递数据到指令的输入属性。


额外排查(若修复后仍报错)

如果xyz.component不属于AppModule的declarations数组,而是属于其他功能模块,需要:

  1. 在AppModule中把MySortGridDirective添加到exports数组
  2. 在xyz.component所属的模块中导入AppModule(或把指令抽离到共享模块,再导入共享模块)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 20:05:06