Обратите внимание, что я только начинаю изучать Angular 9:
Я пытаюсь создать дерево, используя рекурсивный компонент. При каждом рекурсивном вызове компонент получает отдельный объект на @input
, а использование ngOnChanges
выполняет математические вычисления и обновляет этот объект.
Генерация первого дерева в порядке, но при генерации второго и более раз значения умножаются. Из того, что я увидел, соответствующие значения элемента сохраняют значение предыдущего поколения деревьев, которое было изменено на ngOnChanges()
Вот код: Рекурсивный компонент 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)
});}
}
}
Рекурсивный компонент 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;
}
В app.component впервые вызывается рекурсивный компонент
<sf-production2 [item]='selectedItem' [amountNeeded]='2'></sf-production2>
Я пропустил что-то важное? Я делаю это правильно?
Спасибо