Reputation: 11
Note that im just starting to learn Angular 9:
I'm trying to create a tree using a recursive component. On every recursive call component gets a different object on @input
and using ngOnChanges
does some math and updates that object.
First tree generation is fine, but when generating second and more times values are multiplying. From what I saw,item corresponding values retain value from previous tree generation that was changed on ngOnChanges()
Here's code: Recursive Component ts
import { Component, Input, OnChanges } from '@angular/core';
import { IItem, IComponent } from 'src/app/item';
import { notEqual } from 'assert';
import { ItemsService } from 'src/app/items.service';
@Component({
selector:'sf-production2',
templateUrl:'./production.component2.html',
styleUrls:['./production.component2.css']
})
export class ProductionComponent2 implements OnChanges{
@Input() item: IItem
items: IItem[]
@Input() amountNeeded: number;
inputs: IComponent[];
constructor(private itemService: ItemsService){
this.items=itemService.getItems();
}
GetItemByName(name: string){
return this.items.find(x=>x.name === name);
}
ngOnChanges(){
console.log(`${this.item.name}`)
if(this.item.components != null)
{this.item.components.forEach(element => {
console.log(`${element.name}:${element.inputPerMinute}`)
element.inputPerMinute = element.inputPerMinute * (this.amountNeeded/this.GetItemByName(this.item.name).outputPerMin)
});}
}
}
Recursive Component html;
<div *ngFor='let component of item.components'>
<ul>
<img src='{{GetItemByName(component.name).img}}'> {{component.inputPerMinute}}
<sf-production2 *ngIf='GetItemByName(component.name).components' [item]='GetItemByName(component.name)' [amountNeeded]='component.inputPerMinute'></sf-production2>
</ul>
</div>
item.ts
export interface IItem{
name: string;
img: string;
components: IComponent[];
outputPerMin: number;
}
export interface IComponent{
name: string;
inputPerMinute: number;
}
Recursive component gets called for the first time in app.component
<sf-production2 [item]='selectedItem' [amountNeeded]='2'></sf-production2>
Did i miss something crucial? Am i doing it right?
Thanks
Upvotes: 0
Views: 574
Reputation: 49
I would say that the constructor that gets the data from the database is called only once and after that you are constantly operating on the same objects, not on their copies. By such the values that you are updating persist when you select the same object twice.
Upvotes: 1