Angular 4无法绑定 因为它不是一个已知的属性

问题描述 投票:12回答:4

我正在尝试在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

angular typescript angular2-directives
4个回答
19
投票

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

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

有关详细信息,请参阅


3
投票

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

我已修复此问题(父组件测试文件):

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



1
投票

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

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

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

-1
投票

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

@NgModule({
    imports: [TreeViewComponent],
    // This says that all components in this module can import TreeViewComponent
    exports: [ThisModulesComponents],
    declarations: [ThisModulesComponents]
})
export class ModuleDependentOnTreeViewComponent
© www.soinside.com 2019 - 2024. All rights reserved.