'Angular2 wait for @Input object to be fully initialized
I have a .ts class with a variable decorated as @Input
I would like to make a copy of this object but i cant figure out the right place to do this is, my current code:
@Input() myObj: MyObj;
public copy: MyObj;
ngOnInit() {
this.copy = JSON.parse(JSON.stringify(myObj));
}
The call within the ngOnInit method breaks because the ngOnInit is called before the myObj variable is fully created.
I have also tried to create the copy within the ngAfterContentInit method but that is also called before myObj variable is fully created.
I have seen other questions similar to mine, but they all wait for an observable, my object is not an observable, is simply an object passed from parent to child through the view:
<child-view [myObj]="myObjInParent"/>
Solution 1:[1]
It depends when you have to use your copy variable in your code.
You can create a getter which does the parsing if copy is null, and if not you just return the copy value.
It may be null the first few times you call the getter, but eventually once all the datas are loaded the parsing will be done automatically.
Solution 2:[2]
If you want copy to be initialized only once at the time of component initialization then Akmal's solution works: https://stackoverflow.com/a/71093779/904375
But in case you want the copy to be updated every time the @Input() is updated, then you have to create a getter/setter. For eg.:
private _copy: any;
private _employee: Employee;
get employee() { return this._employee; }
@Input() set employee(value: Employee) {
this._employee = value;
this._copy = {...value};
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Christophe b |
| Solution 2 | Zeeshan Siddiqui |
