Angular6: click function only works some of the time


Angular6: click function only works some of the time



I'm using element.scrollIntoView() in my angular app.



I'm getting the desired element to come into view when my click function works.



my TS file:


elem1;
elem2;

ngOnInit() {
this.elem1 = document.getElementById('elem1');
this.elem2 = document.getElementById('elem2')
}

handleElemScroll(elem) {

// elem.scrollTop = 1000;
elem.scrollIntoView({behavior: 'smooth', block: 'end'});

}



And in my template, I am using mat-nav-list, and on click, passing the id of the element and using elem1.scrollIntoView() or elem2.scrollIntoView() to bring the desired element into view (for now bring it into view, but ideally the element should be at the top).





When the click function works, I am able to see both elements come into view on click (scrollIntoView works). But the click behavior is unpredictable. Sometimes the click works and the handleElemScroll() function runs, others time it does nothing.



Any clue as to why this occurs?





I`am not shure that i fully understand problem, but put in handleElemScroll(CLICK EVENT) like handleElemScroll($event). Then symply take a target from event and scroll to it.
– Manfice
Jul 2 at 18:53






the on click doesn't fire every time I click, the scroll event works fine when the click takes place.
– Generaldeep
Jul 2 at 19:16




1 Answer
1



Ok, as i told you before look at this code (Angular 6 in my case, but it must work from 2):


import { Component, OnInit } from '@angular/core';

@Component({
selector: 'eas-requests',
templateUrl: './requests.component.html',
styleUrls: ['./requests.component.css']
})
export class RequestsComponent implements OnInit {

// No need to declare
el1:HTMLElement;
el2:HTMLElement;
constructor() { }

ngOnInit() {
//No need to declare
this.el1 = document.getElementById('el1');
this.el2 = document.getElementById('el2');
}

// Just declare this method and receive html element.
clickEvent(e:HTMLElement){
e.scrollIntoView({behavior: 'smooth', block: 'end'});
}
}



And html:


Element 1

Element 2



In this action you pass click event. So in function you receive HTMLElement what you click. In my case all work fine as expected on any element where i use click event.






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

api-platform.com Unable to generate an IRI for the item of type

PHP contact form sending but not receiving emails

Do graphics cards have individual ID by which single devices can be distinguished?