3

I am trying to create a service for showing alerts (in case sending a form goes wrong). This will be used on various forms of my project so I thought I could use an independant service for this. The problem is: for this alert I need HTML code at a certain place of my form, so what I need to know is : what's best practice for that?

Can I define a template for my service? And how do I use this template in my form wihch uses the service?

Chi
  • 1,320
  • 1
  • 14
  • 48

2 Answers2

2

If showing alerts means showing a popup then it should be a component. Components have a view that is added to the DOM.

You can share a global service that allows other components, directives and services to communicate with your AlertsComponent and pass strings or component types to be shown in the alert. For more details see https://angular.io/docs/ts/latest/cookbook/component-communication.html

I would use ViewContainerRef.createComponent() like demonstrated in Angular 2 dynamic tabs with user-click chosen components to display arbitrary components as content of the alert if you need custom HTML support with Angular bindings in the alert content.

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

I had a difficult time using angular2 packages for notifications then I decided to create my own notification for a system I'm working on. I scrapped online till I found Mathew Ross' Post Check it out and see if it guides you, somehow.

musale
  • 534
  • 8
  • 18
  • that is exaclty what I was looking for! I copied this to start from it but unfortunately _notifications.noteAdded.subscribe is never called - any idea why this might happen? I copied the exact same code and there is no error message – Chi May 23 '16 at 14:01
  • @Chi mine works well... could you post the code for you notification component maybe I could help better? – musale May 23 '16 at 17:56
  • seems I just imported the service at the wrong place, I finally managed to make it work. Thank you so much! – Chi May 24 '16 at 08:33