Let's say there are three categories on the webpage - Continent, Country, State. I am currently working on a button which have been placed on a different page. I want when the button will be clicked my page will automatically redirect to the categories page and scroll to the third section i.e. State section. I am a little new to Angular and have tried a lot's of methods mentioned over the other sites like using RouterLink, navigation, routes but nothing worked as per my expectation as per now. Can someone please assist in this or share some already developed links.
Thanks In Advance.
It easy. Pass state in the router like this on the first page
<button [routerLink] = "['/page2', {pageSec: 'section2'}]">Go to section 2</button>
<br>
<br>
<button [routerLink] = "['/page2', {pageSec: 'section3'}]" >Go to Section 3</button>
Then on the second page, Use the activated route to get the state object from the router. Use the ViewChild decorator to communicate with the DOM. Subscribe to the Activated Route params Observable in ngAfterInit, get the parameter you need, and scroll into view. Check the snippet below to see what I mean
@Component({
selector: 'app-page2',
templateUrl: './page2.component.html',
styleUrls: ['./page2.component.scss']
})
export class Page2Component implements AfterViewInit {
constructor(private http: HttpClient, private activeRoute: ActivatedRoute, ) { }
@ViewChild('container') container: ElementRef<HTMLElement>;
ngAfterViewInit(): void {
this.activeRoute.params.subscribe(param => {
// alert(param.pageSec)
if(param.pageSec){
const section = this.container.nativeElement.querySelector(`#${param.pageSec}`)
console.log(section)
section?.scrollIntoView()
}
})
}
}
On Page2 Html make and a selector. In this example, I made my selector container. Then give each of your sections an id. The id is what your wound scroll into. Your html should look like this.
<div #container>
............
<div id="section1">
.......
</div>
<div id="section2">
....
</div>
<div id="section3">
.....
</div>
</div>
And that's it!!!!. Make sure you use ngAfterInit instead of ngOninit, Because The Dom elements won't be available immediately after you initialize the component