2

Warning!

Before using technique in the answer, please check this issue, which describes error Expression has changed after it was checked. Previous value: 'CD_INIT_VALUE'. I've also provided a pretty (imo) workaround there.

Question

I wrote a popup (dialog) component, which creates a small window in the center of the screen with two buttons and close icon. I want to use this component for a few purposes: prompt, alert, confirmation, etc. So I need defferent templates be conditionally included. Am I right that the only good way is this: to include all code at once and use *ngIf? Or may be I should create one component for prompt, one for confirmation? But in second case I will get some lines of code duplicated.

Tip

You may mant to use this question in cooperation with Angular 2 @ViewChild in *ngIf

Community
  • 1
  • 1
sinedsem
  • 5,413
  • 7
  • 29
  • 46
  • 1
    You can use `ViewContainerRef.createComponent()` in the modal component and just pass the type of the component you want to get displayed in the modal similar to what I explain in http://stackoverflow.com/questions/36325212/angular-2-dynamic-tabs-with-user-click-chosen-components/36325468#36325468 where the type is passed to an `@Input()`. You can also use a shared service to notify the modal component to display a component which makes it easier to address it from anywhere within your app. – Günter Zöchbauer Sep 07 '16 at 05:34
  • 1
    @GünterZöchbauer may be you convert your comment to answer so I can accept it? – sinedsem Sep 08 '16 at 15:18
  • 1
    @GünterZöchbauer assuming you are interested in Angular let me share with you this https://github.com/angular/angular/issues/11007 and this http://plnkr.co/edit/mZSc40KbgBk2azpPVG3g?p=preview – sinedsem Sep 08 '16 at 15:51

1 Answers1

1

You can use ViewContainerRef.createComponent() in the modal component and just pass the type of the component you want to get displayed in the modal similar to what I explain in stackoverflow.com/questions/36325212/… where the type is passed to an @Input().
You can also use a shared service to notify the modal component to display a component which makes it easier to address it from anywhere within your app. See also https://angular.io/docs/ts/latest/cookbook/component-communication.html

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567