角2/4,"ngStyle".应用不同的样式来消除其父元素的活动或不活动 [英] Angular 2/4, "ngStyle". Apply different style depeding its father element active o inactive

查看:63
本文介绍了角2/4,"ngStyle".应用不同的样式来消除其父元素的活动或不活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当父元素被激活时,我需要对元素应用样式.我正在使用routerLinkActive来应用CSS类,并且可以正常工作,但是如果父元素是actite,则可以采用一种内联样式(显示:块),而在其他情况下则应用另一种内联样式(显示:无).

I need to apply a style to an element when it parent element is actived. I'm using routerLinkActive to apply CSS Class and works fine, but deppending if the father element is actite apply one inline style (display: block), in other cases apply another (display: none).

如果父元素处于活动状态:

If parent element is active:

<li class="active">
   <ul class="sub-menu" style="display: block;">
</li>
<li>
   <ul class="sub-menu" style="display: none;">
</li>

当我选择其他元素时:

<li>
   <ul class="sub-menu" style="display: none;">
</li>
<li class="active">
   <ul class="sub-menu" style="display: block;">
</li>

我有一个扩展的项目列表以及它们各自的链接.每个子菜单"都有自己的元素列表.

I have an extended list of items with their respectives Links. Each "sub-menu" has its own list of elements.

推荐答案

如果您想以有角度的方式进行操作,建议您从菜单中制作一个对象或数组,以便您可以对其进行实际的动态更改.时间来使用数据绑定.

If you want to do this the angular way, I'd suggest making an object or array out of your menu so you can make dynamic changes to it in real time using data binding.

要使用Angular创建动态菜单,只需在组件中创建菜单的表示形式.如果您不打算从数据库加载菜单或对其进行更复杂的修改,则可以为它提供静态值.否则,您可以为菜单甚至子菜单创建一个类,以充分利用面向对象编程的优势.

To make a dynamic menu with Angular, simply create a representation of your menu in your component. You can either provide it with static values if you do not plan on loading your menu from a database or making more complex modification to it. Otherwise, you can create a class for your menu and even your sub-menu to take the full advantage of object oriented programming.

组件:

menus: any [] = {
    { subMenus: any [] = { {}, {} }, active: boolean = true; },
    { subMenus: any [] = { {}, {} }, active: boolean = false; }
}

一旦在组件中设置了菜单,就可以通过在html中使用角度数据绑定括号并使用* ngFor来避免完全重复html,从而使其完全动态.

Once you have your menu set up in your component, you can then make it fully dynamic by using angular data binding brackets in your html and using *ngFor to avoid repeating html.

HTML:

<li *ngFor="let menu of menus" [className]="menu.active?'active':''">
   <ul *ngFor="let subMenu of menus.subMenus class="sub-menu" [style.display]="menu.active?'block':'none'">
</li>

您可以使用[ngStyle]一次给出多个样式.

You can use [ngStyle] to give more than one style at a time.

您可以添加

(click)="menu.active=!menu.active"

添加到"li"标签,以使其在单击或点击时处于活动状态或不活动状态

to your 'li' tag to make it active or inactive on a click or

(click)="SetActive(menu)"

在您的组件中创建一个函数,该函数会将单击的菜单旁边的每个菜单设置为非活动状态.

create a function in your component that will set every menu beside the clicked menu to inactive.

这篇关于角2/4,"ngStyle".应用不同的样式来消除其父元素的活动或不活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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