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

Angular自定义指令报错:Can't bind to 'appSmoothHeight'不是div的已知属性

Angular指令绑定错误解决方案

问题描述

开发Angular项目时遇到以下错误:

Error in src/components/parent/parent.component.html (2:6)
Can't bind to 'appSmoothHeight' since it isn't a known property of 'div'.

问题根源

你的SmoothHeightDirective中,指令选择器定义为[appSmoothHeight],但输入属性名称是smoothHeight,二者不匹配。模板中使用[appSmoothHeight]="longContent"绑定时,Angular找不到对应的输入属性,因此触发报错。

解决方法(二选一即可)

方法一:给输入属性添加别名匹配选择器

修改smooth-height.directive.ts中的@Input装饰器,指定别名appSmoothHeight:

import {
  Directive,
  ElementRef,
  HostBinding,
  Input,
  SimpleChanges,
} from '@angular/core';

@Directive({
  selector: '[appSmoothHeight]',
  standalone: true,
})
export class SmoothHeightDirective {
  // 为输入属性指定别名,匹配指令选择器
  @Input('appSmoothHeight') smoothHeight: boolean;
  pulse: boolean;
  startHeight: number;

  constructor(private element: ElementRef) {}

  @HostBinding('@grow')
  get grow() {
    return { value: this.pulse, params: { startHeight: this.startHeight } };
  }

  setStartHeight() {
    this.startHeight = this.element.nativeElement.clientHeight;
  }

  ngOnChanges(changes: SimpleChanges) {
    console.log(changes);
    this.setStartHeight();
    this.pulse = !this.pulse;
  }
}

方法二:修改模板绑定名称匹配输入属性

修改parent.component.html中的绑定语句,使用输入属性原名smoothHeight:

<button (click)="toggleContent()">Toggle Content</button>
<div [smoothHeight]="longContent"></div>

验证

完成上述任一修改后,Angular即可正确识别指令的输入属性,绑定错误将被修复。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 05:37:01