I am reading this Angular doc, it says:
With any object-like expression—such as object, Array, Map, or Set—the identity of the object must change for Angular to update the class list. Updating the property without changing object identity has no effect.
So, how do I change an object’t identity?
Thanks.
Advertisement
Answer
The wording there is slightly unfortunate. You can’t really change an object’s identity – the identity is that object. It’s like trying to make X not X. What it means is that a new object or array needs to be created for Angular to detect it as different. For a tiny example in vanilla JS:
const isSameObject = (obj1, obj2) => obj1 === obj2; console.log(isSameObject({}, {})); // false, different objects const someObj = {}; const sameReferenceToSomeObj = someObj; sameReferenceToSomeObj.newProp = 'newVal'; console.log(isSameObject(someObj, sameReferenceToSomeObj)); // true, same object
For Angular to detect a change the identity on a property, the property value must be changed to a new value, rather than having the old value mutated. The second example in the snippet above is an example of how not to do things in Angular; mutating an object doesn’t change its identity (it’s still the same object), so if you did that in Angular, it would see that the old object on the property is ===
to the new object on the property, and would not produce a visual change as a result.
Create an entirely new object instead, with the desired properties, and put that object on the component, and then Angular will be able to see that the new object is not ===
to the old object, and take the appropriate action as a result, eg
this.theClassList = { ...this.theClassList, newProperty: 'foo' }
and not
const newClassList = this.theClassList; newClassList.newProperty = 'foo'; this.theClassList = newClassList;