2

I'm new to angular2 (and angular overall) and I'm trying to envision how to integrate angular components with a legacy java app. I'm trying to build a transition path to a SPA like experience, and that means for some time I need to blend the tech stacks.

Specifically, I'm wondering if I were to include a root angular 2 component on a page how I could inject a static JavaScript object into it to (as opposed to building a back end api to serve that data).

For example, I envision something like:

<body>
    <my-app [appContext]=appContext>
<\body>

I know that can't work, but I'm not sure how else to ask. I think during that app loading phase when we bind the angular component to the dom element we might be able to inject a JavaScript object into the my-app class. Either that or perhaps the my-app class can access a globally scoped JavaScript object that's declared outside of angular?

Patrick
  • 35
  • 5

1 Answers1

1
Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Thanks. I'm feeling a bit dumb here - trying to use the first approach and finding that elementRef.nativeElement.getAttribute("appCtxt") is null. In my index.html I have
    some context
    . What am I missing here?
    – Patrick Nov 05 '16 at 03:09
  • Can you provide more information? Perhaps in a Plunker – Günter Zöchbauer Nov 05 '16 at 09:54
  • For some reason plunker was struggling with adding the ElementRef... here's my github for the sandbox i created: https://github.com/patrickkee/angular2-sandbox – Patrick Nov 05 '16 at 10:50
  • Worked fine for me https://plnkr.co/edit/OdDAdvbRoebfKhEvDcic?p=preview – Günter Zöchbauer Nov 05 '16 at 10:52
  • 1
    Nevermind i got it: i didnt know to do this: – Patrick Nov 05 '16 at 10:57
  • This seems so trivial but now I don't know how to make "somevalue" a javascript object rather than a string literal. Can it do that or can i only pass text in? Must I pass a json string in and load it into a javascript object? I want to define a global javascript object and pass that in... – Patrick Nov 05 '16 at 11:20
  • Attributes only support strings. I guess you can use `JSON.parse()` – Günter Zöchbauer Nov 05 '16 at 11:22
  • 1
    Hmmk. I guess now I'll try pulling in a global js variable. – Patrick Nov 05 '16 at 12:13
  • Would you mind providing more info on how to access a global js variable from window.appContext within angular2? – Patrick Nov 05 '16 at 12:49
  • Does `console.log(window.appContext);` not work for you? You need to ensure the varible is set before Angular loads otherwise it might not yet be available when you try to read it. – Günter Zöchbauer Nov 05 '16 at 12:50
  • Well, i found this plunker which looks like a decent implementation but I haven't gotten it working locally yet. http://plnkr.co/edit/ceuEBlVpWhNNYZvMOqbO?p=preview – Patrick Nov 05 '16 at 14:49