반응형
Angular 구성 요소 외부에서 클릭 감지
Angular에서 구성 요소 외부 의 클릭을 어떻게 감지 할 수 있습니까?
import { Component, ElementRef, HostListener, Input } from '@angular/core';
@Component({
selector: 'selector',
template: `
<div>
{{text}}
</div>
`
})
export class AnotherComponent {
public text: String;
@HostListener('document:click', ['$event'])
clickout(event) {
if(this.eRef.nativeElement.contains(event.target)) {
this.text = "clicked inside";
} else {
this.text = "clicked outside";
}
}
constructor(private eRef: ElementRef) {
this.text = 'no clicks yet';
}
}
AMagyar의 답변에 대한 대안. 이 버전은 ngIf로 DOM에서 제거되는 요소를 클릭 할 때 작동합니다.
http://plnkr.co/edit/4mrn4GjM95uvSbQtxrAS?p=preview
private wasInside = false;
@HostListener('click')
clickInside() {
this.text = "clicked inside";
this.wasInside = true;
}
@HostListener('document:click')
clickout() {
if (!this.wasInside) {
this.text = "clicked outside";
}
this.wasInside = false;
}
위에서 언급 한 답변은 정확하지만 관련 구성 요소에서 초점을 잃은 후 무거운 프로세스를 수행하는 경우 어떻게해야합니까? 이를 위해 포커스 아웃 이벤트 프로세스가 관련 구성 요소에서만 포커스를 잃을 때만 발생하는 두 개의 플래그가있는 솔루션을 제공했습니다.
isFocusInsideComponent = false;
isComponentClicked = false;
@HostListener('click')
clickInside() {
this.isFocusInsideComponent = true;
this.isComponentClicked = true;
}
@HostListener('document:click')
clickout() {
if (!this.isFocusInsideComponent && this.isComponentClicked) {
// do the heavy process
this.isComponentClicked = false;
}
this.isFocusInsideComponent = false;
}
이것이 당신을 도울 것입니다. 놓친 것이 있으면 정정하십시오.
https://www.npmjs.com/package/ng-click-outside 패키지 에서 clickOutside () 메서드를 사용할 수 있습니다.
참고URL : https://stackoverflow.com/questions/40107008/detect-click-outside-angular-component
반응형
'Program Tip' 카테고리의 다른 글
$ {}와 # {}의 차이점은 무엇입니까? (0) | 2020.10.24 |
---|---|
Angular 2-라우팅-Observable로 CanActivate 작업 (0) | 2020.10.23 |
System.Net.Http 4.2.0.0의 이상한 문제를 찾을 수 없습니다. (0) | 2020.10.23 |
HTML에서 입력 및 텍스트 입력 선택-동일한 너비를 만드는 가장 좋은 방법은 무엇입니까? (0) | 2020.10.23 |
codeigniter 이메일 라이브러리를 사용하여 Gmail SMTP로 이메일 보내기 (0) | 2020.10.23 |