角度隐藏显示不起作用

时间:2017-02-18 11:07:46

标签: angular angular-components

当我点击一个父母时,所有父母都会使用hide来渲染他们的孩子。我是棱角分明的新人。请推荐。

所以我有以下组件

import { Component, Input } from '@angular/core';

@Component( {
    selector: 'sidebar-cmp',
    templateUrl: 'sidebar.html',
    styleUrls: [
         'sidebar.scss'
    ]
})

export class SidebarComponent {
    @Input() tenants = 0;
    showMenu: string = '';

    addExpandClass( element: any ) {
        if ( element === this.showMenu ) {
            this.showMenu = '0';
        } else {
            this.showMenu = element;
        }
    }
}

相应的HTML

<nav class="sidebar">
    <ul class="list-group" *ngFor="let tenant of tenants ;trackBy: trackId">
        <div class="nested-menu">
            <a class="list-group-item" (click)="addExpandClass('tenant.id')">
                <span><i class="fa fa-th-list"></i> &nbsp; {{tenant.name}}</span>
            </a>
            <li class="nested" [ngClass]="{'expand' : showMenu === 'tenant.id' }">
                <ul class="submenu">
                    <li>
                        <a href><span>Submenu</span></a>
                    </li>
                    <li>
                        <a href><span>Submenu</span></a>
                    </li>
                </ul>
            </li>
        </div>       
    </ul>
</nav>

enter image description here

2 个答案:

答案 0 :(得分:0)

看起来你在传递字符串,而不是变量:

    <a class="list-group-item" (click)="addExpandClass('tenant.id')">
        <span><i class="fa fa-th-list"></i> &nbsp; {{tenant.name}}</span>
    </a>

试试这个:

    <a class="list-group-item" (click)="addExpandClass(tenant.id)">
        <span><i class="fa fa-th-list"></i> &nbsp; {{tenant.name}}</span>
    </a>

并据此:

<li class="nested" [ngClass]="{'expand' : showMenu === tenant.id }">

答案 1 :(得分:0)

You are mistake in writing the [ngClass] 'tenant.id' is not a string. So why are pass as string.

<nav class="sidebar">
    <ul class="list-group" *ngFor="let tenant of tenants ;trackBy: trackId">
        <div class="nested-menu">
            <a class="list-group-item" (click)="addExpandClass('tenant.id')">
                <span><i class="fa fa-th-list"></i> &nbsp; {{tenant.name}}</span>
            </a>
            <li class="nested" [ngClass]="{'expand' : showMenu === tenant.id }">
                <ul class="submenu">
                    <li>
                        <a href><span>Submenu</span></a>
                    </li>
                    <li>
                        <a href><span>Submenu</span></a>
                    </li>
                </ul>
            </li>
        </div>       
    </ul>
</nav>