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

Angular12子组件继承基类@Input后报Can't bind to 'data'错误求助

问题根因

Angular 只有被@Directive或@Component装饰的类,其内部的@Input/@Output等装饰器元数据才会被子类继承。你当前给抽象基类加的是@Injectable()装饰器,这个装饰器仅用于服务类,不会保存输入输出相关的元数据,因此子类ChildComponent无法继承到data输入属性的声明,Angular 编译时就会判定app-child不存在data属性,抛出绑定错误。

解决方案

修改base.component.ts的装饰器即可,将@Injectable()替换为空的@Directive()装饰器:

import { Directive, OnInit, Input } from '@angular/core';

// 替换原有的@Injectable()
@Directive()
export abstract class BaseComponent implements OnInit {
  @Input() data: string[] | undefined;
  constructor() {}

  ngOnInit(): void {}
}

修改后重新编译项目,绑定错误会直接消失,父组件传递的fruits数据可以正常被基类的data输入属性接收,子组件模板可以正常渲染列表。

替代方案(不推荐)

如果暂时不想修改基类,也可以在子类中重新声明@Input()属性,手动转发给父类,不过该方案会失去继承复用的意义:

// child.component.ts
export class ChildComponent extends BaseComponent implements OnInit {
  @Input() override data: string[] | undefined;
  // 其余逻辑不变
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 20:54:05