마우스 이벤트 전파 중지
Angular에서 마우스 이벤트 전파를 중지하는 가장 쉬운 방법은 무엇입니까?
내가 특별하게 합격해야 합니까?$event
and 의기제이stopPropagation()
나 자신 혹은 다른 방법이 있습니다.
예를 들어, 유성에서 나는 간단히 돌아올 수 있습니다.false
이벤트 핸들러에서.
동일한 코드를 반복적으로 복사/붙여넣지 않고 요소에 추가하려면 이 작업을 수행하도록 지시할 수 있습니다.이는 다음과 같이 간단합니다.
import {Directive, HostListener} from "@angular/core";
@Directive({
selector: "[click-stop-propagation]"
})
export class ClickStopPropagation
{
@HostListener("click", ["$event"])
public onClick(event: any): void
{
event.stopPropagation();
}
}
그런 다음 원하는 요소에 추가합니다.
<div click-stop-propagation>Stop Propagation</div>
가장 간단한 방법은 이벤트 핸들러에서 전파 중지를 호출하는 것입니다. $event
Angular 2에서도 동일하게 작동하며 진행 중인 이벤트(마우스 클릭, 마우스 이벤트 등)를 포함합니다.
(click)="onEvent($event)"
이벤트 핸들러에서 전파를 중지할 수 있습니다.
onEvent(event) {
event.stopPropagation();
}
이벤트를 호출하면 전파가 차단됩니다.
(event)="doSomething($event); $event.stopPropagation()"
그냥 답례로false
(event)="doSomething($event); false"
하면 여러 식을수.;
에서 처럼.*.ts
files 파일
는 마막식결원인됩이니다가과의지를 유발할 입니다.preventDefault
거짓일 경우 호출됩니다.따라서 표현식이 반환하는 내용에 주의하십시오(하나만 있는 경우에도).
@Android University의 답변에 추가.한 줄로 다음과 같이 쓸 수 있습니다.
<component (click)="$event.stopPropagation()"></component>
이것은 저에게 효과가 있었습니다.
mycomponent.component.ts:
action(event): void {
event.stopPropagation();
}
mycomponent.component.component:
<button mat-icon-button (click)="action($event);false">Click me !<button/>
해야만 했어요stopPropagation
그리고.preventDefault
버튼이 위에 있는 아코디언 항목을 확장하는 것을 방지하기 위해.
그래서...
@Component({
template: `
<button (click)="doSomething($event); false">Test</button>
`
})
export class MyComponent {
doSomething(e) {
e.stopPropagation();
// do other stuff...
}
}
이벤트에 바인딩된 메서드의 경우 false를 반환하기만 하면 됩니다.
@Component({
(...)
template: `
<a href="/test.html" (click)="doSomething()">Test</a>
`
})
export class MyComp {
doSomething() {
(...)
return false;
}
}
방금 Angular 6 애플리케이션을 체크인했는데, event.stopPropagation()은 $event를 넘기지 않고 이벤트 핸들러에서 작동합니다.
(click)="doSomething()" // does not require to pass $event
doSomething(){
// write any code here
event.stopPropagation();
}
IE(Internet Explorer)에서는 작동하지 않았습니다.제 테스터들은 뒤에 있는 버튼의 팝업 창을 클릭하여 제 모달을 깰 수 있었습니다.그래서 저는 제 모달 화면 디비를 클릭하는 것을 듣고 팝업 버튼에 다시 초점을 맞추었습니다.
<div class="modal-backscreen" (click)="modalOutsideClick($event)">
</div>
modalOutsideClick(event: any) {
event.preventDefault()
// handle IE click-through modal bug
event.stopPropagation()
setTimeout(() => {
this.renderer.invokeElementMethod(this.myModal.nativeElement, 'focus')
}, 100)
}
사용한
<... (click)="..;..; ..someOtherFunctions(mybesomevalue); $event.stopPropagation();" ...>...
간단히 말해서, ';'로 다른 것/함수 호출을 구분하고 $event.stopPropagation()을 추가합니다.
JavaScript와의 href 링크 사용 안 함
<a href="#" onclick="return yes_js_login();">link</a>
yes_js_login = function() {
// Your code here
return false;
}
Angular와 함께 TypeScript에서 작동하는 방법 (My Version: 4.1.2)
Template<a class="list-group-item list-group-item-action" (click)="employeesService.selectEmployeeFromList($event); false" [routerLinkActive]="['active']" [routerLink]="['/employees', 1]">
RouterLink
</a>
TypeScript
public selectEmployeeFromList(e) {
e.stopPropagation();
e.preventDefault();
console.log("This onClick method should prevent routerLink from executing.");
return false;
}
그러나 routerLink!의 실행을 비활성화하지는 않습니다.
false after 함수를 추가하면 이벤트 전파가 중지됩니다.
<a (click)="foo(); false">click with stop propagation</a>
이를 통해 이벤트가 아이들에 의해 발사되는 것을 방지할 수 있었습니다.
doSmth(){
// what ever
}
<div (click)="doSmth()">
<div (click)="$event.stopPropagation()">
<my-component></my-component>
</div>
</div>
이 지시문 사용
@Directive({
selector: '[stopPropagation]'
})
export class StopPropagationDirective implements OnInit, OnDestroy {
@Input()
private stopPropagation: string | string[];
get element(): HTMLElement {
return this.elementRef.nativeElement;
}
get events(): string[] {
if (typeof this.stopPropagation === 'string') {
return [this.stopPropagation];
}
return this.stopPropagation;
}
constructor(
private elementRef: ElementRef
) { }
onEvent = (event: Event) => {
event.stopPropagation();
}
ngOnInit() {
for (const event of this.events) {
this.element.addEventListener(event, this.onEvent);
}
}
ngOnDestroy() {
for (const event of this.events) {
this.element.removeEventListener(event, this.onEvent);
}
}
}
사용.
<input
type="text"
stopPropagation="input" />
<input
type="text"
[stopPropagation]="['input', 'click']" />
제공되는 솔루션의 대부분은 Angular 11 이상 버전, Angular 11 이하 버전에 대해 사용할 수 있는 해결 방법을 찾았습니다.
export class UiButtonComponent implements OnInit, OnDestroy {
@Input() disabled = false;
clickEmitter: Subject<any> = new Subject();
constructor(private elementRef: ElementRef) { }
ngOnInit(): void {
this.elementRef.nativeElement.eventListeners()
.map(listener => this.clickEmitter.pipe(filter(event => Boolean(event))).subscribe(event => listener(event)));
this.elementRef.nativeElement.removeAllListeners();
this.elementRef.nativeElement.addEventListener('click', (event) => {
if (!this.disabled) {
this.clickEmitter.next(event);
}
});
}
ngOnDestroy(): void {
this.clickEmitter.complete();
}
}
기본적으로 모든 청취자를 현재 구성요소로 이동하여 관찰 가능한 구성요소에 배치한 다음 한 명의 청취자만 등록하고 작업을 관리합니다.
위의 예는 부울 변수가 지정된 버튼에서 클릭 이벤트를 비활성화하는 예입니다.
언급URL : https://stackoverflow.com/questions/35274028/stop-mouse-event-propagation
'itsource' 카테고리의 다른 글
사용자 지정 오류 모드="Off" (0) | 2023.04.27 |
---|---|
@module/material/index.d.ts'는 모듈이 아닙니다. (0) | 2023.04.27 |
패널 또는 플레이스홀더 사용 (0) | 2023.04.22 |
"sh" 또는 "bash" 명령을 사용하지 않고 셸 스크립트를 실행하려면 어떻게 해야 합니까? (0) | 2023.04.22 |
약한 참조와 소유하지 않은 참조의 차이점은 무엇입니까? (0) | 2023.04.22 |