bounty 2 天后到期。这个问题的答案有资格获得 +50 声望奖励。
nclskfm想引起对这个问题的更多关注。
我简化了我的问题:
<div *ngIf="layout1" class="layout1">
<div class="sidebar-layout1">
some items
</div>
<child-component [something]="sth"></child-component>
</div>
<div *ngIf="!layout1" class="layout2">
<child-component [something]="sth">
<p>some content...</p>
</child-component>
</div>
我有一个父组件,它有可能是正常布局(layout1)和全屏布局(layout2)(在全屏模式下,子组件应该是全屏的)。问题是,
当我使用 *ngIf 更改布局时,子组件将被销毁并生成一个新组件。我想拥有相同的实例并且不要丢失子组件的重要信息并避免一些api调用。
有什么方法可以实现子组件不会被破坏或者有比 ngIf 更好的方法吗?
对于父组件中的不同布局,我只需要一个子组件实例。
最佳答案
正如您可能已经注意到的,如果您使用 *ngIf
隐藏元素然后创建一个新组件。这是我们将重点关注并尽量避免创建新组件的内容。
为此,我们可以使用“切换器布局”并将子组件作为内容传递
<app-layout-switcher [layout1]="layout1">
<ng-container>
<child-component
*ngIf="sth$ | async as sth; else loading"
[something]="sth"
>
<p>some content...</p>
</child-component>
<ng-template #loading>
<h1>Loading...</h1>
</ng-template>
</ng-container>
</app-layout-switcher>
我添加了一个模拟 http 调用来显示加载。在我们的
app-layout-switcher
组件我们可以根据需要在布局之间切换。我们将通过child-component
到模板中,以便能够在布局中重用它<div *ngIf="layout1">
<app-layout-1>
<ng-template [ngTemplateOutlet]="childComponent"></ng-template>
</app-layout-1>
</div>
<div *ngIf="!layout1">
<app-layout-2>
<ng-template [ngTemplateOutlet]="childComponent"></ng-template>
</app-layout-2>
</div>
<ng-template #childComponent>
<ng-content></ng-content>
</ng-template>
现在我们可以在我们的布局中使用模板<header>
<h1>Layout 1</h1>
</header>
<main>
Contents in Layout 1
<div>
<ng-content></ng-content>
</div>
</main>
<footer>Layout 1 Footer</footer>
我们现在只使用组件的一个实例。为了确认这一点,我在演示中添加了一个文本字段。你会注意到切换布局时数据是持久化的See this Demo
关于Angular 6 - 多个子组件应该是同一个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51037349/