Apply toggle function to only clicked element using pure java script

时间:2017-10-12 09:47:28

标签: javascript html angular

This is my html code where i'm displaying data

<ul id="menu">
<li *ngFor="let category of componentContents.dashboardMenu;let i = index" >
    <p (click)="toggle_visibility()"class="parent-menu">{{category.category}</p>
    <ul id="{{(category.category).split(' ').join('-')}}" class="toggled" 
        *ngIf="category.subCategory.length > 0" style="display:none">
        <li *ngFor="let subCat of category.subCategory"> 
            <a routerLink={{subCat.router}} routerLinkActive="active"  
            {{subCat.subcategory}}</a>
        </li>
    </ul>
</li>

This is the function where i'm trying to display sub menus on click but all the sub menus of all p tags are getting displayed.I want to apply toggle function to only clicked p element.

toggle_visibility() {
    var pm = document.getElementByClassName('parent-menu');
    var e = document.getElementsByClassName('toggled');
    for (let i = 0; i < pm.length; i++) {
        if (e[i].style.display == 'block' || (e[i].style.display == '') {
                e[i].style.display = 'none';
                }
                else {
                    e[i].style.display = 'block';
                    }
                };
            }

As i'm new to java script and angular 2. Need help to figure this out.

1 个答案:

答案 0 :(得分:1)

You should rather use

[style.display]="e[i].style.display == '' ? 'none' : 'block'"
(click)="toggle_visibility(i)"
toggle_visibility(i) {
  this.e[i] = !this.e[i];
}

where e is an array with the same number of items as componentContents.dashboardMenu