skip to Main Content

I have an application with mega navigation which have list of items. Within another component I have same list with accordions. When I click on a item in mega nav it is redirecting to the component and accordion is going to expand of selected item.it is working fine. Now I want to scroll down to the expanded div when page is loading.

This is my code looks like

<div class="container">
<hr>
<div *ngFor="let category of parentData| async; let i = index" class="category-content">
  <div class="expanded-div" *ngIf="collapsible == category.id">
    
     {expanded accordion data goes here }}
  
  </div>


  <div *ngIf="collapsible != category.id">

     {{non-expanded accordion data goes here}}

  </div>
</div>

I tried anchor tag method also. But it is not working.
I tried this.

I tried this also in my .ts file inside the ngOninit()

document.getElementById("expanded-div").scrollIntoView();

it gives me below error.

Object is possibly ‘null’. ts(2531)

can someone help me to resolve this issue.

2

Answers


  1. You have not provided id to corresponding block in html code.
    You can do it like this:

    <div class="expanded-div" id="expanded-div" *ngIf="collapsible == category.id">
        
         {expanded accordion data goes here }}
      
      </div>
    

    or

    in your .ts file use document.getElementsByClassName() instead of document.getElementById().

    Hope this helps!

    Login or Signup to reply.
  2. It says "object is possibly null" because when you call any element selector like getElementById or getElementsByClassName it’s possible that no elements will match the selector and it will return null. Run this example to see what I mean

    console.log(
      document.getElementById('example')
    );
    
    console.log(
      document.getElementById('not-on-the-page')
    );
    <span id="example">Hello</span>

    Typescript it catching this possible error for you, so you need to deal with the fact that your selector might be null. There are two ways you can do this:

    1.) This is the best way. you save the element as a variable, and then check to see if that variable has a value or not.

    const myEl = document.getElementById("expanded-div");
    if(myEl){
      myEl.scrollIntoView();
    } else {
      console.error('The element could not be found!')
    }
    

    2.) This will work, but I do not recommend it. By adding a ! it’s called a "non-null assertion" and this means you are telling TypeScript "I know better than you, and this element will exists 100% of the time no matter what. I do not recommend this way because if you are wrong, then your application will have a runtime error. This is much more fragile than the above method.

    document.getElementById("expanded-div")!.scrollIntoView();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search