I have component and render it in cycle (ngFor) The component has an object
@Input() a = {
name: 'Bob'
}
After the change, it will reset its input parameters to the initial state
When the component has changed, I want to get the values that were at its initial initialization
SCENARIO:
-> @Input() a = {name: 'Bob'} (init value)
-> then do something... this.a.name = 'Alice';
-> in the loop, the object changes
-> Once again, the component matters @Input() a = {name: 'Bob'} (init value)
I want to get the previous value after the component has been updated
that is 'Alice'
From the angular documentation:
ngOnChanges(changes: SimpleChanges) {
if(changes.a) {
let chng = changes.a;
let cur = JSON.stringify(chng.currentValue);
let prev = JSON.stringify(chng.previousValue);
}
}
So, you'll need the .currentValue and .previousValue property to access current and previous values.
Edit:1
If the component gets destroyed you have to use some kind of state management - service with subject, sessionStorage, localStorage or something else
Edit: 2
You can extend the ngFor directive and add the state logic inside ngOnChanges.
@Directive({
selector: '[ngFor][ngForIn]'
})
export class NgForIn extends NgFor implements OnChanges {
@Input() ngForIn: any;
constructor(viewContainer: ViewContainerRef,
template: TemplateRef<NgForRow>,
differs: IterableDiffers,
cdr: ChangeDetectorRef) {
super(viewContainer, template, differs, cdr);
}
ngOnChanges(changes: SimpleChanges): void {
// Do something here
}
}