JBoy
JBoy

Reputation: 5745

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"/>

Upvotes: 0

Views: 1350

Answers (3)

Zeeshan S.
Zeeshan S.

Reputation: 2091

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};
  };
 
  

Upvotes: 0

Christophe b
Christophe b

Reputation: 14

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.

Upvotes: 0

Akmal
Akmal

Reputation: 395

One way you could possibly do it is to place an *ngIf on the like this

<child-view *ngIf="myObjInParent" [myObj]="myObjInParent"/>

That would essentially display the component only after the myObjInParent changes from undefined to your value. Not the best solution, but it works.

Also you can make a copy of an object using an ES6 spread operator

this.copy = {...myObj}

using a three dot notation. Hope I could help!

Upvotes: 2

Related Questions