首页 > 解决方案 > 数据绑定不能跨角度的不同模块发生吗?

问题描述

我一直在尝试改进我的应用程序——而不是成为一个在 app 模块中声明所有内容的单一应用程序——我想将某些组件移动到功能模块中。但是,在我从一个组件到模块外部的另一个组件的某些数据绑定的地方,这破坏了代码。

ResultDetailsComponent 模板

            <div class="col-9">
              <app-links-table [loaded]="dataLoaded" [dataLinkResult]="dataLinkResult"></app-links-table>
            </div>

ResultDetailsComponent 现在属于我在其中声明和导出它的ItemsModule 。

@NgModule({
  declarations: [
    ResultDetailsComponent,

  ],
  exports: [
    ResultDetailsComponent
  ]
})
export class ItemsModule { }

LinksTableComponent (app-links-table)包含数据绑定的正确输入

export class LinksTableComponent {

  @Input() loaded: boolean;
  @Input() dataLinkResult: Link[];

}

目前,这仍然在主AppModule中声明,尽管我计划将其移出到它自己的功能模块中。

@NgModule({
  declarations: [
    LinksTableComponent,
  ],
  exports: [
    LinksTableComponent
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

答案是我现在需要创建一个服务来在这些组件之间进行通信吗?或者我的结构有什么根本错误?

标签: angular

解决方案


将组件重构为单个模块总是好的。

模块在 Angular 中形成编译上下文。但是在执行此操作时,您需要注意几件事...

  1. 有些功能模块您不会在其他模块中导入(至少不是很多)。
  2. 您将在所有或大部分功能模块中导入共享模块。

因此,请查看如何按照上述要点使用链接表组件并重构您的代码。

关于错误...

如前所述,模块形成了一个编译上下文。所以如果你想在模块“a”的组件中使用模块“b”的组件,模块“a”必须导入模块“b”(现在不要在其他模块中导入应用程序模块:P。重构以移动组件进入另一个模块)。

一切顺利。


推荐阅读