Angular库自定义HeaderDirective无法绑定:提示属性未识别
解决Angular库指令绑定错误:Can't bind to 'layoutHeaderTitle' since it isn't a known property of 'div'
问题场景
我在Angular库中开发了HeaderDirective指令,代码如下:
@Directive({ selector: '[layoutHeaderTitle]', standalone: true }) export class HeaderDirective { constructor( readonly tpl: TemplateRef<any>, private readonly headerService: HeaderService) { this.headerService.headerTitleTpl = tpl; } ngOnDestroy(): void { console.log('DESTROY'); this.headerService.clear(); } }
库的public-api.ts已导出该指令,layout.module.ts也已声明并导出该指令,项目的app.module.ts已导入LayoutModule。但在项目中使用<div [layoutHeaderTitle]>title</div>时,出现错误:
Can't bind to 'layoutHeaderTitle' since it isn't a known property of 'div'
解决步骤
1. 修正指令的使用方式
你的指令选择器[layoutHeaderTitle]是属性选择器,但模板中用了[layoutHeaderTitle](方括号)会被Angular识别为属性绑定,而指令未定义对应的@Input()属性,因此报错。
- 若无需传递值,直接以属性形式使用:
<div layoutHeaderTitle>title</div> - 若需要绑定值,给指令添加同名
@Input():
此时即可用@Directive({ selector: '[layoutHeaderTitle]', standalone: true }) export class HeaderDirective { // 添加与选择器同名的Input,支持绑定语法 @Input() layoutHeaderTitle?: any; constructor( readonly tpl: TemplateRef<any>, private readonly headerService: HeaderService) { this.headerService.headerTitleTpl = tpl; } ngOnDestroy(): void { console.log('DESTROY'); this.headerService.clear(); } }<div [layoutHeaderTitle]="someValue">title</div>的方式使用。
2. 确认库的构建与模块配置
- 重新构建库(执行
ng build your-library-name),确保项目使用的是最新的库代码。 - 检查
layout.module.ts的声明与导出是否正确:
由于指令标记了@NgModule({ declarations: [HeaderDirective], exports: [HeaderDirective] }) export class LayoutModule {}standalone: true,也可以跳过模块,直接在项目的模块/组件中导入独立指令:// 在app.module.ts或使用指令的组件中导入 imports: [HeaderDirective]
3. 校验public-api.ts的导出
确保public-api.ts正确导出指令和模块:
export * from './path/to/header.directive'; export * from './path/to/layout.module';
项目中需从库的根路径导入,避免直接引用库内部文件。
内容的提问来源于stack exchange,提问作者Iraklis Bekiaris
相关产品推荐
相关产品推荐

