简体   繁体   中英

Angular 2 how to prevent data binding for specific variable

So I need to prevent data binding for a specific variable. I want to do it like this:

// data is mostly an object in my case.
// it would be nice if there's a global solution
function(data) {
    d = data; // variable that changes on user input
    oldD = data; // variable that shouldn't change on user input
}

but whenever I implement code like this the oldD variable will change when the d variable gets changed. And I would like to prevent this from happening. But how do I prevent such a thing?

You need to assign value without assigning reference of old object.

Here's solution for JavaScript/Angular.

let oldD = Object.assign({}, data);

Hope this helps.

Probably you are looking for, How to clone object.

function(data) {
    d = data; // variable that changes on user input  

    // creates brand new object with the same data
    let oldD = Object.create(data.constructor.prototype);
    data.constructor.apply(oldD);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM