What I am trying to do is to create an anchor link. This link will navigate to a specific scroll point in my page. I have Angular version 5.
Html:
<mat-list>
<mat-list-item><a [routerLink]="['/']"> Intro </a></mat-list-item>
<mat-list-item><a [routerLink]="['/']" fragment="mobile"> Mobile </a></mat-list-item>
...
</mat-list>
In home.componets.ts:
export class HomeGrComponent implements OnInit {
private fragment: string;
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.route.fragment.subscribe(fragment => { this.fragment = fragment; });
}
ngAfterViewInit(): void {
try {
setTimeout(()=> {
document.querySelector('#' + this.fragment).scrollIntoView();
}, 1000);
} catch (e) { }
}
}
I took this code from this question but it doesn't work. Url is changed to
http://localhost:4200/#mobile
but it didn't scroll to my point. Also in console there is an error:
Cannot read property 'scrollIntoView' of null
What can be possible goes wrong? If you need some additional information please ask me to reply. Also it could be great the scroll navigates smoothly (optional).