I have a small expression to check whether 2 objects are different or not, in order to display this element (via adding class name):
<div ngClass='{{JSON.stringify(obj1) != JSON.stringify(obj2) ? "div-show" : ""}}'></div>
The problem is I get this error:
Cannot read property 'stringify' of undefined
.
What I need a way to work around, or a proper solution if available. Thanks.
PS: I use JSON.stringify() to compare 2 simple objects, nothing fancy here.
Angular Json Pipe converts a value or object into JSON formatted string. Usually we will get the data from the server in JSON format, and we will bind it to HTML. To know the exact JSON data coming from the server we can use network tab in browser developer tools.
The JSON. stringify() function, as name suggests, converts a JavaScript value to a serialized JSON string. JSON. stringify() can optionally use a replacer function to replace values using custom logic.
stringify() The JSON. stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
The JSON. parse() function is used to convert a string into a JavaScript object while the JSON. stringify() function is used to convert a JavaScript object into a string.
Template code doesn't have access to all javascript, only component properties and methods. I think it would be best to create a 'stringify' method on your component, but you could just set a JSON property:
public constructor() {
this.JSON = JSON;
}
Also I think your expression is backwards. NgClass
takes the css class as the property name and a true/false value to tell whether that class is on the element, and it needs to be in brackets:
<div [ngClass]="{'div-show': JSON.stringify(obj1) != JSON.stringify(obj2)}"></div>
2 Years later but, you can do it the Angular Way using the built in pipe 'JsonPipe' from @angular/common
@Component({
selector: 'json-pipe',
template: `<div>
<p>Without JSON pipe:</p>
<pre>{{object}}</pre>
<p>With JSON pipe:</p>
<pre>{{object | json}}</pre>
</div>`
})
export class JsonPipeComponent {
object: Object = {foo: 'bar', baz: 'qux', nested: {xyz: 3, numbers: [1, 2, 3, 4, 5]}};
}
you can achieve it like this in your component do this.
myjson:any=JSON;
and in you view do it like this
<div ngClass='{{myjson.stringify(obj1) != myjson.stringify(obj2) ? "div-show" : ""}}'></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With