-->

Angular 2/4, “ngStyle”. Apply different style depe

2019-07-25 03:04发布

问题:

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>

When I choose another element:

<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.

回答1:

This can be achieved with CSS only:

.sub-menu {
  display: none;
}

.active .sub-menu {
  display: block;
}

Check out this live demo to see how it works.



回答2:

If you use a boolean flag template variable:

<li [class.active]="flag">
   <ul class="sub-menu" [style.display]="flag ? 'block' : 'none'">
</li>
<li>
   <ul class="sub-menu" [style.display]="flag ? 'none' : 'block'">
</li>

You can also use the router active directive to control the flag:

<li [class.active]="link.isActive" #link="routerLinkActive">

And use link.isActive instead of flag elsewhere.



回答3:

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.

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.

Component:

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

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>

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

You can add

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

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.