Angular报错:无法绑定到'authorize',它不是'li'的已知属性
首先,这个报错 Can't bind to 'authorize' since it isn't a known property of 'li' 本质是Angular无法在当前模块中识别你的AuthorizeDirective,结合你的模块配置描述,最可能的遗漏点有两个,另外还有一个语法适配的细节需要注意:
1. 最关键的遗漏:SharedModule没有导出AuthorizeDirective
Angular模块里的组件、指令、管道默认只能在本模块内部使用。如果要让其他模块(比如你的HeaderModule)共享SharedModule里的指令,必须把它加入到SharedModule的exports数组中——只在declarations里声明是不够的,那只是告诉Angular“这个模块拥有这个指令”,但不会对外暴露。
修改你的SharedModule代码:
@NgModule({ declarations: [AuthorizeDirective], exports: [AuthorizeDirective], // 必须加上这一行,把指令导出给其他模块使用 }) export class SharedModule { }
2. 确认HeaderModule已导入SharedModule
如果HeaderModule没有显式导入SharedModule,即使SharedModule导出了指令,HeaderComponent所在的模块也无法访问到它。检查HeaderModule的配置,确保它导入了SharedModule:
@NgModule({ declarations: [HeaderComponent], imports: [SharedModule], // 加上这一行,导入SharedModule以使用其中的指令 }) export class HeaderModule { }
额外细节:指令类型与模板语法匹配
你在模板中用了*authorize的语法,这表示你把它当作结构型指令(用来控制DOM元素的添加/移除),但目前你的AuthorizeDirective并没有注入结构型指令必需的TemplateRef和ViewContainerRef,也没有实现渲染/销毁模板的逻辑。
如果你的意图确实是做结构型指令(比如根据权限显示/隐藏元素),需要补充指令的核心逻辑:
import { Directive, OnInit, Input, TemplateRef, ViewContainerRef } from '@angular/core'; @Directive({ selector: '[authorize]' }) export class AuthorizeDirective implements OnInit { private notifier: Subscription; requirement: Requirement; id: number; // 注入结构型指令必需的依赖 constructor( private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef ) {} @Input() set authorize(requirement: string) { this.requirement = Requirement[requirement]; } @Input() set authorizeId(id: number) { this.id = id; } ngOnInit() { // 根据你的权限逻辑,决定是否渲染模板 if (this.checkAuthorization()) { this.viewContainer.createEmbeddedView(this.templateRef); } else { this.viewContainer.clear(); } } // 示例权限检查方法,替换成你的实际业务逻辑 private checkAuthorization(): boolean { // 比如判断用户是否已登录等 return true; } }
如果只是想做属性指令(比如修改元素样式、绑定事件等,不需要控制DOM的存在与否),则需要去掉模板中的*,写成属性绑定的形式:
<li [authorize]="'SignedIn'"><button (click)="signIn()">Sign In</button></li>
内容的提问来源于stack exchange,提问作者Miguel Moura

