繁体   English   中英

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

[英]Angular 4 Can't bind to <property> since it isn't a known property of <component>

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

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

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

有关详细信息,请参阅

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

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

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


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

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

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

如果您在另一个模块使用TreeViewComponent,你需要将部件导入@NgModule如下:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM