【问题标题】:Angular2 replacing component dynamically inside another componentAngular2在另一个组件内动态替换组件
【发布时间】:2016-04-27 23:34:09
【问题描述】:

我正在尝试将组件加载到具有自己视图的其他组件中。将要加载的组件将是动态的并且基于某些条件。

我的意思是替换父组件内相同位置的另一个组件。

例如,在我的 AppComponent.html(如下)中,我想加载可以再次被具有某些事件的其他组件替换的组件。

AppComponent.html

<button class="button1">Button1 </button>
<button class="button2">Button2 </button>
<placeHolder></placeHolder>

AppComponent.ts

@Component({
    selector: '...',
    templateUrl: 'resources/app.component.html'
})
export class AppComponent{
     //on click of the button1, I want to load component c1, and on click of button2, I want to load component c2
}

(c1 和 c2 只是任何其他组件)

如何做到这一点?非常感谢任何帮助。

【问题讨论】:

  • 请添加一些代码来演示您尝试完成的工作。
  • Günter - 乍一看,我认为这是一个非常不同的主题 (stackoverflow.com/questions/36325212/…),但我想在你的回答中你使用过 DynamicComponentLoader,我会尝试这个,希望这会为我工作..虽然我已经按照您要求进行更具体的查询进行了编辑。希望这对你有意义。
  • 如果你想在&lt;placeHolder&gt;标签处加载和卸载,那么DCL(DynamicComponentLoader)应该是适合你的。
  • 好的,谢谢...如果您愿意,可以将其写为答案,因为我认为这将是一个更通用的答案,并且我认为这对其他用户会有所帮助。
  • DCL 在 beta.16 中发生了相当大的变化。我还没有更新链接的答案。 stackoverflow.com/questions/35170985/… 已经更新,以备不时之需。

标签: angular


【解决方案1】:

如果你想在&lt;placeHolder&gt;标签处加载和卸载,那么DCL(DynamicComponentLoader)应该是适合你的选择

有关示例,请参阅 Angular 2 dynamic tabs with user-click chosen components

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-05
    • 2017-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-21
    • 2018-12-31
    相关资源
    最近更新 更多