You might want to look for similar questions related to AngularJS, not Angular 2 specific, as the main gist of the thing remains the same:
- you want your server-side Razor engine to render some kind of view (i.e. HTML or JS directly)
- this view contains a JS template where part of the content is filled from a server model instance or anyway server data (e.g. a resource, dictionary, etc.)
- in order to properly fill a JS variable from Razor, C# server-side data has to be properly serialized into a JSON format
In this post by Marius Schulz you can see as he serializes the data and uses that to fill a template AngularJS value
component:
<script>
angular.module("hobbitModule").value("companionship", @Html.Raw(Model));
</script>
Something similar could be made to inject some data e.g. into window.myNamespace.myServerData
, and then have Angular2 bootstrap that value among other providers.
In this post by Roel van Lisdonk, a similar approach is used, again, to fill an AngularJS-based template, with that ng-init
directive:
<div ng-controller="main"
ng-init="resources={ textFromResource: '@WebApplication1.Properties.Resources.TextFromResource'}">
<h1>{{ title }}</h1>
{{ resources.textFromResource }}
</div>
As the first post points out, there's something to think about (pasting here):
A word of caution: The method I'm about to use is probably not a good fit for large amounts of data. Since the JavaScript data is inlined into the HTML response, it's sent over the wire every single time you request that page.
Also, if the data is specific to the authenticated user, the response can't be cached and delivered to different users anymore. Please keep that in mind when considering to bootstrap your Angular Apps with .NET data this way.
The second part may be less of an issue if your served page is already dynamic server-side, i.e. if it already has bits filled in out of server-side data.
HTH