Angular 2 ngfor show component in array

I have an array of components, I want to show existing components in this array, but it does not work, I suspect that the new component is created and shown in ngfor, and not in the array, because I see new components are created, but with a default value but not the current value that is 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); 
+6
source share
1 answer

Create an array of VisualTextDivComponent for the array of objects. Pass this array to ngFor . Then pass each element of the array to your app-visual-text-div component as follows:

 <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 --> 
+3
source

Source: https://habr.com/ru/post/1013508/


All Articles