Passing parameter to angular2 app from a .cshtml view rendering in SiteCore

212 Views Asked by At

I have a view rendering written in .cshtml. The .cshtml in turn refers .js files (written as angular2 apps). I want to pass a parameter from the .cshtml to the angular2 app. How do I do this? I am using angular-cli to generate the angular2 app.

2

There are 2 best solutions below

0
Jens Mikkelsen On

I would just output the value in a JavaScript namespace inside a script tag in your view/controller rendering and then use that in your Angular app. Eg. output this:

<script type="text/javascript">
  var solution = solution || {};
  solution.vars = solution.vars || {};
  solution.vars.myVariable = '@Model.MyVariable';
</script>

Then you can just access the solution.vars.myVariable in your other JavaScript.

0
Jeroen On

Jens answer will definitely work. You could also pull the data with a separate call through Sitecore Service Client in Angular if you are concerned with adding variables to global scope or don't want to have additional dependencies on the view. This will have a small performance impact as an additional request would need to be made.