1

im working on angular2 typescript project ,I just want to reset the object's key to '' after calling save( ) function , example is below

export class Events{
    event:any={ name : '', date : '',.........};
    eventOriginal=this.event;

    save(){

      //save(this.event)

      //after save, reset value to initial state

      this.event=this.eventOriginal;

    }

  }

but in console.log(this.event) the value is not cleared, both objects are same. i tried to assign value from constructor too, so, what is the proper way to reset keys of object in typescript ?

2 Answers 2

2

When you assign an object to another you are only assigning the reference.

Quick fix

Clone the object using spread

export class Events{
    event={ name : '', date : '',.........};
    eventOriginal= {...this.event};
Sign up to request clarification or add additional context in comments.

2 Comments

Does the OP code even work? class Events { eventOriginal = this.event } -> this.event === window.event?
{...this.event}; seems it does not support in my typescript version
1

The step eventOriginal=this.event; will just assign the reference in javascript.

The Object.assign() method should be used to copy the values of all enumerable own properties. like

eventOriginal = Object.assign({}, this.event);

and then later

this.event= Object.assign({}, this.eventOriginal);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.