In an ember component template how can I use 'if' to check for at least one of an array having a property equal to X?

蹲街弑〆低调 提交于 2019-12-13 04:59:35

问题


My component is passed a notification.

A notification has an account, and an account has many contacts.

So I could easily do something like

{{#if (is-greater-than notification.account.contacts.length 0)}}
  <p>stuff</p>
{{/if}}

To check for the existence of a contact, but what if I wanted to only display if at least one contact has firstName 'John', how could I do this in the component template only? Or if not possible in the template what is the next best approach?

I tried having a isHidden property in my component and then in the didInsertElement hook looping through contacts and then communications with the aim of checking myself - however I find contact.get('communications').forEach doesn't get hit because that level of data hasn't been pulled from the server at that point.


回答1:


For the first question, you could write a helper to do that:

// helpers/contains-john.js
export default function(array) {
    return array.any((item) => item.get('firstName') === 'John');
};

Then use it as a subexpression just like you have above:

{{#if (contains-john notification.account.contacts)}}
    Stuff
{{/if}}


来源:https://stackoverflow.com/questions/31456016/in-an-ember-component-template-how-can-i-use-if-to-check-for-at-least-one-of-a

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!