Angular 4에서 클릭시 요소로 스크롤
버튼을 눌렀을 때 대상으로 스크롤하고 싶습니다. 나는 이런 생각을하고 있었다.
<button (click)="scroll(#target)">Button</button>
그리고 내 component.ts에서 같은 방법.
scroll(element) {
window.scrollTo(element.yPosition)
}
위의 코드는 유효하지 않지만 내가 생각하는 것을 보여주기위한 것임을 압니다. 저는 Angular에 대한 이전 경험이없이 Angular 4를 배우기 시작했습니다. 나는 이와 같은 것을 찾고 있었지만 모든 예제는 Angular 4와 많이 다른 AngularJs에 있습니다.
다음과 같이 할 수 있습니다.
<button (click)="scroll(target)"></button>
<div #target>Your target</div>
그런 다음 구성 요소에서 :
scroll(el: HTMLElement) {
el.scrollIntoView();
}
편집 : 요소가 정의되지 않아 더 이상 작동하지 않는다는 주석이 표시됩니다. Angular 7에서 StackBlitz 예제 를 만들었는데 여전히 작동합니다. 누군가 작동하지 않는 예를 제공 할 수 있습니까?
다음은 앵귤러 4를 사용하여 수행 한 방법입니다.
주형
<div class="col-xs-12 col-md-3">
<h2>Categories</h2>
<div class="cat-list-body">
<div class="cat-item" *ngFor="let cat of web.menu | async">
<label (click)="scroll('cat-'+cat.category_id)">{{cat.category_name}}</label>
</div>
</div>
</div>
이 기능을 구성 요소에 추가하십시오.
scroll(id) {
console.log(`scrolling to ${id}`);
let el = document.getElementById(id);
el.scrollIntoView();
}
실제로 setTimeout
또는 requestAnimationFrame
또는 jQuery 를 사용하지 않고이를 수행하는 순수한 자바 스크립트 방식이 있습니다.
간단히 말해서 scrollView에서 스크롤하려는 요소를 찾아 scrollIntoView
.
el.scrollIntoView({behavior:"smooth"});
여기에 plunkr가 있습니다.
Jon은 정답을 가지고 있으며 이것은 내 각도 5 및 6 프로젝트에서 작동합니다.
클릭하여 navbar에서 바닥 글로 부드럽게 스크롤하려면 :
<button (click)="scrollTo('.footer')">ScrolltoFooter</button>
<footer class="footer">some code</footer>
scrollTo(className: string):void {
const elementList = document.querySelectorAll('.' + className);
const element = elementList[0] as HTMLElement;
element.scrollIntoView({ behavior: 'smooth' });
}
바닥 글에서 머리글로 다시 스크롤하고 싶었 기 때문에이 함수가있는 서비스를 만들어 navbar 및 바닥 글 구성 요소에 삽입하고 필요한 곳에 'header'또는 'footer'를 전달했습니다. 실제로 사용 된 클래스 이름을 구성 요소 선언에 제공하는 것을 기억하십시오.
<app-footer class="footer"></app-footer>
이 파티에 조금 늦었지만 Angular 4+ 용 플러그인을 작성했습니다. 서버 측 렌더링과 같이 부딪 힐 수있는 다른 문제를 다룹니다. 원하는대로 스크롤하도록 애니메이션 할 수도 있습니다. 전체 공개, 내가 저자입니다.
NPM : @ nicky-lenaers / ngx-scroll-to
GitHub : @ nicky-lenaers / ngx-scroll-to
도움이 되었기를 바랍니다.
각도 7에서 완벽하게 작동합니다.
HTML
<button (click)="scroll(target)">Click to scroll</button>
<div #target>Your target</div>
구성 요소에서
scroll(el: HTMLElement) {
el.scrollIntoView({behavior: 'smooth'});
}
각도에서 ViewChild 및 ElementRef를 사용할 수 있습니다. html 요소에 ref를 제공하십시오.
<div #myDiv >
구성 요소 내부 :
import { ViewChild, ElementRef } from '@angular/core';
@ViewChild('myDiv') myDivRef: ElementRef;
this.myDivRef.nativeElement를 사용하여 요소로 이동할 수 있습니다.
Angular에서 수행하는 또 다른 방법 :
마크 업 :
<textarea #inputMessage></textarea>
ViewChild () 속성 추가 :
@ViewChild('inputMessage')
inputMessageRef: ElementRef;
scrollIntoView () 함수를 사용하여 구성 요소 내부에서 원하는 곳으로 스크롤합니다.
this.inputMessageRef.nativeElement.scrollIntoView();
You can scroll to any element ref on your view by using the code block below. Note that the target (elementref id) could be on any valid html tag.
On the view(html file)
<div id="target"> </div>
<button (click)="scroll()">Button</button>
on the .ts file,
scroll() {
document.querySelector('#target').scrollIntoView({ behavior: 'smooth', block: 'center' });
}
I have done something like what you're asking just by using jQuery to find the element (such as document.getElementById(...)) and using the .focus() call.
You can do this by using jquery :
ts code :
scrollTOElement = (element, offsetParam?, speedParam?) => {
const toElement = $(element);
const focusElement = $(element);
const offset = offsetParam * 1 || 200;
const speed = speedParam * 1 || 500;
$('html, body').animate({
scrollTop: toElement.offset().top + offset
}, speed);
if (focusElement) {
$(focusElement).focus();
}
}
html code :
<button (click)="scrollTOElement('#elementTo',500,3000)">Scroll</button>
Apply this on elements you want to scroll :
<div id="elementTo">some content</div>
Here is a stackblitz sample.
참고URL : https://stackoverflow.com/questions/43945548/scroll-to-element-on-click-in-angular-4
'program tip' 카테고리의 다른 글
SELECT 쿼리에 대한 SQL Server 잠금 이해 (0) | 2020.11.03 |
---|---|
Android에서 콜백이란 무엇입니까? (0) | 2020.11.03 |
HAX 커널 모듈이 설치되지 않았습니다. (0) | 2020.11.03 |
Android-툴바의 표준 높이 (0) | 2020.11.03 |
127.0.0.1:27017에 연결하지 못했습니다. 이유 : errno : 111 연결이 거부되었습니다. (0) | 2020.11.03 |