Angular 2根据管道结果添加样式 [英] Angular 2 add style based on pipe result

查看:164
本文介绍了Angular 2根据管道结果添加样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定是否可行.

<span class="nav-label second-level-text" style="margin-left: 10px;">
{{partner.name}}
    <span class="badge"
      *ngIf="unreadConversations.length > 0 | unreadConversationForPartner : [unreadConversations,partner.id]">
    {{unreadConversations.length | unreadConversationForPartner : [unreadConversations,partner.id]}}
    </span>
</span>

我在这边.我将过滤器应用于*ngIf,并显示返回的过滤器的值(即计数)

I have the span over here. And I am applying filter to the *ngIf and also displaying the value of returned filter(which is the count)

如果从管道返回的计数大于0,我想显示一种样式,否则不显示该样式.但是,我可以通过*ngIf and Filter来实现,但是如果Filter的值被更改,则*ngIf不会更改.

I will like to display a style if the count returned from the pipe is greater than 0, and if not don't display the style. However I am able to achieve this by *ngIf and Filter but if the value of the Filter is changed, then the *ngIf doesnot change.

例如.我在数组中有2个项目.

For instance. I have 2 items in the array.

第1项:长度为1,它显示跨度并执行其工作...

Item 1: The length is 1 and it displays the span and does its job...

第2项:开始时长度为0,并且不显示(这是正确的行为),但是过滤器值发生了变化,但是随后又没有再次调用*ngIf.

Item 2: At start the length is 0 and it does not display ( which is right behaviour) but the filter value changes, but then the *ngIf is not called again.

unreadConversationForPartner pipe

transform(value: any, ...args: any[]): any {
        var count = 0;
        var partnerId = args[0][1];
        var conversations = args[0][0];
        conversations.forEach(element => {
            if(element.partnerId == partnerId) count++
        });
        return count;
    }

让我知道所提供的信息是否足够或不清楚.

Let me know if the information provided is not enough or clear.

推荐答案

您可以使用前一段时间介绍的as

You can use as that was introduced a while ago

*ngIf="unreadConversations.length > 0 | unreadConversationForPartner : [unreadConversations,partner.id] as result"

然后在其他指令或绑定中使用它

and then use it in other directives or bindings

[ngStyle]="{backgroundColor: result >= 5 ? 'red' : 'blue'}"

另请参见 https://angular.io/api/common/NgIf#storing-conditional-result-in-a-variable

这篇关于Angular 2根据管道结果添加样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆