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
You have not provided id to corresponding block in html code.
You can do it like this:
or
in your
.ts
file usedocument.getElementsByClassName()
instead ofdocument.getElementById()
.Hope this helps!
It says "object is possibly null" because when you call any element selector like
getElementById
orgetElementsByClassName
it’s possible that no elements will match the selector and it will returnnull
. Run this example to see what I meanTypescript 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.
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.