简体   繁体   中英

In Angular2 *ngFor loop cannot create canvas elements from array of objects

In my TypeScript class I can load an array of type HTMLCanvasElement - but when I iterate over this array with ngFor - I only see text on the page for each canvas object loaded: "[object HTMLCanvasElement]".

The gist of my template code:

<div>*ngFor="#cvs of canvases">  
{{cvs}} </div>

Relevant Class code:

canvases:HTMLCanvasElement[]=[]
var canvas = document.createElement("canvas");
//here I take an image and drawimage via context -- this part works
//then......
this.canvases.push(canvas);

My assumption is probably wrong-headed: but, if you can append a canvas object to a node (which I can do) - then why can you not place the canvas object onto the window "directly" inside a div using *ngFor?

  • Create a componenet with image and other options required as @Input()
  • Move your canvas creation code in the component
  • In the component you have shown make canvases an array of objects that contains the information for each canvas
  • In ngFor render the canvas component you created by passing info to your component

Your code is not working because you are trying to stringify the HTMLCanvasElement inside ngFor using interpolation {{}}

Here is the working Plunker https://plnkr.co/edit/1ho41z

  • Instead of push html objects around use javascript objects.
  • Let HTML create HTML elements instead of using document.createElement
  • Avoid using document.getElementById inside Angular component
  • See usage of View Child to get hold of components

There is still scope of improvements in the plunker, but you get the gist of creating a component in Angular with the plunk above

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM