1

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.

5
  • Formatting the code properly would help a lot ;-) Commented Oct 12, 2017 at 9:48
  • You should rather use [style.display]="e[i].style.display == 'block' ? '' : 'block'" instead of doing it in code. Commented Oct 12, 2017 at 9:50
  • Thanks but this code is applying on all clicked p elements how can i make it to work on only clicked element Commented Oct 12, 2017 at 9:55
  • Your way of reading and accessing the DOM is totally against how it should be done in Angular. Commented Oct 12, 2017 at 9:55
  • See my answer below. Pass the index to toggleVisibility and maintain the state of each entry in an array. Commented Oct 12, 2017 at 9:55

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

How will I access e inside toggle function?
e has to be an array of booleans the same size as componentContents.dashboardMenu There is no need to access the DOM, because you know in the components class how many elements there will be from the size of componentContents.dashboardMenu
Please edit your question and add the code you have now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.