Home > database >  Angular2 wait for @Input object to be fully initialized
Angular2 wait for @Input object to be fully initialized

Time:02-13

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

CodePudding user response:

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!

  • Related