Html 在 Angular2 模板的表达式中使用 JSON.stringify

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38622470/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 13:38:34  来源:igfitidea点击:

Using JSON.stringify in an expression in Angular2 template

htmlangular

提问by Pho Huynh

I have a small expression to check whether 2 objects are different or not, in order to display this element (via adding class name):

我有一个小表达式来检查 2 个对象是否不同,以显示此元素(通过添加类名):

<div ngClass='{{JSON.stringify(obj1) != JSON.stringify(obj2) ? "div-show" : ""}}'></div>

The problem is I get this error: Cannot read property 'stringify' of undefined.

问题是,我得到这个错误: 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.

PS:我使用 JSON.stringify() 来比较 2 个简单的对象,这里没什么特别的。

回答by Jason Goemaat

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:

模板代码无法访问所有 javascript,只能访问组件属性和方法。我认为最好在您的组件上创建一个 'stringify' 方法,但您可以只设置一个 JSON 属性:

public constructor() {
  this.JSON = JSON;
}

Also I think your expression is backwards. NgClasstakes 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:

我也认为你的表达是倒退的。 NgClass将 css 类作为属性名称和一个 true/false 值来判断该类是否在元素上,并且需要放在括号中:

<div [ngClass]="{'div-show': JSON.stringify(obj1) != JSON.stringify(obj2)}"></div>

回答by Marcos R

2 Years later but, you can do it the Angular Wayusing the built in pipe 'JsonPipe' from @angular/common

2 年后,您可以使用来自@angular/common 的内置管道“JsonPipe”以Angular 方式进行操作

@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]}};
}

回答by rashfmnb

you can achieve it like this in your componentdo this.

你可以在你的组件中像这样实现它。

myjson:any=JSON;

and in you viewdo it like this

在你看来这样做

<div ngClass='{{myjson.stringify(obj1) != myjson.stringify(obj2) ? "div-show" : ""}}'></div>