根据 angular 中的用户选择动态替换主要组件内容

replace main component content dynamically based on user selection in angular

我的 angular 项目中有一个主要组件,应根据用户从组件 user.summary.component 中选择的所有其他组件的数据更新和替换该组件。我的主要组件位于页眉和页脚之间,我有一个名为 user.summary.component 的左侧导航,用户可以在其中选择他的个人资料信息、银行卡信息、帐户偏好、订单。

当用户从 user.summary.component 中选择个人资料信息时,我的主要组件应使用个人资料信息详细信息进行更新。同样,卡信息、帐户偏好和订单信息应该替换主要组件内容。

我的 main.component.html 看起来像这样:

<p>
  main-body loaded!
</p>

<!-- multi slot transclusion here -->
<ng-content select="[body-content]"></ng-content>
<ng-content select="[body-header]"></ng-content>
<ng-content select="[body-footer]"></ng-content>

当用户从 user.summary.component 中选择 profile.information link 时,profile.information。组件应该替换主组件模板内容:

<app-main-body>

  <h4 body-content>  profile info body content here</h4>
  <h4 body-header> profile header here</h4>
  <h4 body-footer>  profile footer here</h4>

</app-main-body>

当用户从 user.summary.component 中选择 account.preferences link 时,account.preferences.component 应该替换主组件模板内容:

<app-main-body>

  <h4 body-content>  account preferences body content here</h4>
  <h4 body-header> account preferences header here</h4>
  <h4 body-footer>  account preferences footer here</h4>

</app-main-body>

我浏览了此博客上的几篇文章,能够弄清楚如何将数据从组件传递到另一个组件,但无法弄清楚如何替换主要组件内容并根据用户选择注入模板。

Angular 2 passing value between components

我不确定我是否理解你的问题,但这里有两种方法可以实现这一点。

1) 将组件与 *ng-if

一起使用

2) 使用路由

但是对于这两种方法,您都需要为每个个人资料信息、银行卡信息、帐户偏好和订单创建单独的组件。

如果您想使用 *ng-if 执行此操作,请按以下步骤操作。

main.component.html

<user.summary [onSectionChange]="changeSection($event)"></user.summary>

<profile.info *ngIf="selected == '1'"></profile.info>
<card.info *ngIf="selected == '2'"></card.info>
<account.pref *ngIf="selected == '3'"></account.pref>
<orders *ngIf="selected == '3'"></orders>

main.component.ts

selected: number = 1; // show profile.info by default
...
onSectionChange(section: number) {
  this.selected = section;
}

user.summary.component.ts

...
onSelectView(option: number) {
  this.onSectionChange.emit(option);
}