6

i have an array of components, i want to show the existing components in that array but it doesnt work, i suspect that a new component is created and showed in the ngfor and not the one in the array because i do see new components get created but with a default value and not the current value that get passed to them, what am i doing wrong?

html:

<div #visualTextDiv class = "visual_text" [ngStyle]=setStyles()>

  <div *ngFor="let lineCounter of visualDivArray">
    <app-visual-text-div></app-visual-text-div>
  </div>

</div>

typescript:

if(this.visualDivArray.length < currentDivIndex+1){
  let newv = new VisualTextDivComponent()
  this.visualDivArray.push(newv);
  console.log("creating new " + this.visualDivArray.length);
}

this.visualDivArray[currentDivIndex].setData(textValue);
ppovoski
  • 4,553
  • 5
  • 22
  • 28
dvrer
  • 589
  • 6
  • 17
  • What do you mean with "existing components in that array". Angular doesn't render components from an array. – Günter Zöchbauer Dec 25 '16 at 19:21
  • @GünterZöchbauer so i cannot have an array and populate it with components instances and make it render by ngfor? – dvrer Dec 25 '16 at 19:24
  • Don't think so. `new VisualTextDivComponent()` doesn't give you a component, only a instance of the components class. Perhaps this approach provides some ideas http://stackoverflow.com/questions/36325212/angular-2-dynamic-tabs-with-user-click-chosen-components/36325468#36325468 – Günter Zöchbauer Dec 25 '16 at 19:26
  • @GünterZöchbauer thanks for the referance :), i could make the components add him self in his constructor to an array and then i could manipulate it but its "up side down". – dvrer Dec 25 '16 at 19:31
  • 1
    Why don't you have an array of plain objects, iterate over these objects, and pass the object as input to your app-visual-text-div component? That's how angular is supposed to be used: your model contains data, not components, and data is passed as input to components. – JB Nizet Dec 25 '16 at 19:50

1 Answers1

3

Have your VisualTextDivComponent create an array of objects. Pass that array to the ngFor. Then pass each item of the array into your app-visual-text-div component like this:

<div #visualTextDiv class = "visual_text" [ngStyle]=setStyles()>
  <div *ngFor="let lineCounter of visualDivArray">
    <app-visual-text-div [curLineCounter]="lineCounter"></app-visual-text-div>
  </div>   
</div>

curLineCounter or some better name, is a variable in the app-visual-text-div component.

AppVisualTextDiv.ts

import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-visual-text-div',
  templateUrl: './AppVisualTextDiv.html'
})
export class AppVisualTextDiv{  
  @Input() curLineCounter: {
    'id': number,
    'someValue': string,
  };
}

AppVisualTextDiv.html

<div id="{{curLineCounter.id}}">
  <span>{{curLineCounter.someValue}}</span>
</div>
<!-- or whatever your use case provides -->
ppovoski
  • 4,553
  • 5
  • 22
  • 28