Angular 4无法绑定到<property>,因为它不是<component>的已知属性

时间:2017-03-31 02:09:54

标签: angular typescript angular2-directives

我正在尝试在Angular 4中创建自己的指令。但是,当将类的属性绑定到组件模板时,我遇到了这个错误。

控制台错误:

Unhandled Promise rejection: Template parse errors: Can't bind to
'data' since it isn't a known property of 'tree'. ("<tree [ERROR
->][data]="data"></tree>"):

我的tree-view-component.ts:

@Component({
    selector: 'app-tree-view',
    template: '<tree [data]="data"></tree>'
})
export class TreeViewComponent implements OnInit {

    @Input() data: any[];

    constructor() {
        this.data = [
        {
            label: 'a1',
            subs: [
                {
                    label: 'a11',
                    subs: [
                        {
                            label: 'a111',
                            subs: [
                                {
                                    label: 'a1111'
                                },
                                {
                                    label: 'a1112'
                                }
                            ]
                        },
                        {
                            label: 'a112'
                        }
                    ]
                },
                {
                    label: 'a12',
                }
            ]
         }
     ];
  }

  ngOnInit() { }

}

这是我的完整脚本文件:https://pastebin.com/hDyX2Kjj

有没有人知道这件事? TIA

4 个答案:

答案 0 :(得分:14)

每个组件,指令和管道都需要在@NgModule()

中注册
@NgModule({
  declarations: [TreeViewComponent]
})
export class AppModule {}

有关详细信息,请参阅

答案 1 :(得分:1)

对ParentComponent运行测试时,我遇到了相同的错误。里面是具有@Input属性:string;的ChildComponent组件。 这两个组件也都在app.module.ts中声明。

我已经这样修复(父组件测试文件):

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ParentComponent, ChildComponent]// added child component declaration here
    })
      .compileComponents();
  }));


答案 2 :(得分:0)

As Aelfinn 指出,如果您在模块之间使用组件,则需要将其导出。 但是你不应该导入,导出并在你想要使用它的模块中声明它,因为它不是这个模块的一部分!
假设你有一个声明 TreeViewComponent TreeViewStuffModule 和一个使用TreeViewComponent的 DoSomethingWithTreeViewModule ,你的声明如下:

@NgModule({
  declarations: [
    TreeViewComponent
  ],
  exports: [
    TreeViewComponent
  ]
})
export class TreeViewStuffModule { }

@NgModule({
  imports: [
    TreeViewStuffModule
  ]
})
export class DoSomethingWithTreeViewModule

答案 3 :(得分:-1)

如果您在其他模块中使用 TreeViewComponent ,则需要组件导入@NgModule,如下所示:

@NgModule({
    imports: [TreeViewComponent],
    // This says that all components in this module can import TreeViewComponent
    exports: [ThisModulesComponents],
    declarations: [ThisModulesComponents]
})
export class ModuleDependentOnTreeViewComponent