1202 Program Alarm 1202 Program Alarm - 6 months ago 17
AngularJS Question

Dynamic instantiation of Components?

Update: To clarify my sad verbiage below...

Given an array of JSON objects, a "Level" component and a "Sprite" component...

I'm stuck on the syntax to loop through the array and init a new "Sprite" for each JSON object and then add that "Sprite" to ... the template (?) of my "Level".

This is my "Level" template. I can hardcode the Sprite in and it works (as the image shows) but I'm scrambling to find the syntax to add an arbitrary number of Sprites.



<div>
<img src={ {imagePath}}/>
</div>
<div>
<app-sprite></app-sprite>
</div>








I'm a refugee Flex/Actionscript developer and am learning Angular 2. I "get" lots of it – but then I get stuck.

My little exercise here: based on some JSON (hard-coded now but later to come from a Service) is to populate a "Level" component with a background image, and then create and position some "Sprites" on the "Level".

Here's the way it looks now:

enter image description here

I've created a plunk of what I am doing. Where I am confused:


  • How do I dynamically create custom components the "angular" way? I've seen the tutorials with
    *ngFor
    to create
    li
    elements but the template for my "Sprite" component looks like this:





<div>
<img class="spriteFloater" src={{imagePath}}/>
</div>`





The above works if I hardcode the "imagePath" to a url – but if I try to use "eventData.imagePath" (where event data is a JSON obj) then it fails.

I can hard-code that a reference to that template into my "Level" ("app-sprite" tags) and it works but my attempts to generate "Sprites" on the fly have failed.


  • Also, I am trying to pass data to each "Sprite" and then use it in my template. I tried doing it through the
    constructor
    but that didn't work so a created a custom function to do it – and while it outputs the correct data to the console, the "Sprites" I am creating are not the ones being injected into the DOM.



Geez... sorry this is such a stupid, wordy post.

Answer

I guess you just need to use

eventData?.imagePath

If you init data in ngOnInit() this is after Angular first tries to resolve bindings in the view. If eventData is null the access to imagePath throws. With ?. Angular accesses imagePath only when eventData is != null

Comments