0

(Plunker of the problem at hand.)

I'm trying to initialize a number of Angular 2 components programatically from the constructor, like this:

constructor() {
  this.cells = [];
  for (let i = 0; i < 4; i++)
  {
    this.cells[i] = new CellComponent();
    this.cells[i].setNumber(i+1);
  }
  console.log(this.cells);
}

However, it seems that even though the console output reads:

enter image description here

I get this as the initial HTML:

enter image description here

What am I missing here? Why aren't the calls to setNumber() in the constructor reflected in the DOM? Also, why isn't the cellUpdated event fired when I call setNumber()?

Vilinkameni
  • 266
  • 1
  • 4
  • 12
  • Not sure what you try to accomplish. Do you by any chance assume that the component instances in the `cells` array are related to the `` elements in the components template? That's not the case. – Günter Zöchbauer Nov 11 '16 at 19:51
  • 3
    Remove `#cell` from your template. You're trying to get value from uninitialized object. I don't understand why you're using the same class like model – yurzui Nov 11 '16 at 19:55
  • @GünterZöchbauer Yes, I assumed such. It is not the case, why? – Vilinkameni Nov 11 '16 at 19:57
  • @yurzui Thanks, that actually helped! New fork: https://plnkr.co/edit/conZ46RHIIvMqhW6925I?p=preview – Vilinkameni Nov 11 '16 at 19:57
  • If you use `new CellComponent();` then you get an instances of this class and there is nothing that would related it to anything in the view. You don't create components with `new()`. You create them by adding an element with a matching selector to the template of another component and Angular2 creates the component for you. – Günter Zöchbauer Nov 11 '16 at 19:59
  • @GünterZöchbauer Ah, but I added `` elements which traversed through the `cells` array with `*ngFor`. – Vilinkameni Nov 11 '16 at 20:01
  • Hard to tell where your thinking is wrong. I would say start with not using `new` with component classes never ever. You won't need this in an Angular2 application (perhaps in unit tests but not in the application code). – Günter Zöchbauer Nov 11 '16 at 20:08
  • @GünterZöchbauer My use case would be, for example, to fill a grid of products in response to an AJAX call. I'd need to retrieve a list as a JSON-encoded string, then unpack it and add the components to a grid. Or that wouldn't be the correct approach? – Vilinkameni Nov 11 '16 at 20:14
  • See http://stackoverflow.com/questions/36325212/angular-2-dynamic-tabs-with-user-click-chosen-components/36325468#36325468 and replace grid cell with tab – Günter Zöchbauer Nov 11 '16 at 20:15

0 Answers0