Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 2 ngfor show component in array

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);
like image 831
dvrer Avatar asked Dec 25 '16 19:12

dvrer


1 Answers

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 -->
like image 143
ppovoski Avatar answered Nov 16 '22 21:11

ppovoski