我有一個指令僅適用于其他角度應用程式,但在具有角度的 Ionic 中卻沒有。
該指令檢查用戶是否已登錄,如果沒有,則打開帶有一些說明的彈出視窗。
當用戶未登錄時,我有彈出視窗并且可以作業,但是盡管使用了 preventDefault/stopPropagation 等,但該事件的觸發方式相同。
這是代碼:
View.component.html
<ion-icon name="pricetag-outline" onlyLogged authorized="true" (click)="saveNews(news)" ></ion-icon>
僅記錄的.directive.ts
import { Directive, ElementRef, OnInit, HostListener, Input } from '@angular/core';
import { PopoverController } from '@ionic/angular';
import { AuthService } from '../services/auth.service';
import { OnlyLoggedComponent } from '../components/only-logged/only-logged.component';
@Directive({
selector: '[onlyLogged]'
})
export class OnlyLoggedDirective implements OnInit {
@Input() authorized = false;
isUserLogged: boolean;
constructor(private auth: AuthService, public popoverController: PopoverController) { }
@HostListener('click', ['$event'])
clickEvent(event) {
if (!this.isUserLogged) {
console.log(event);
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
event.returnValue = false;
event.buttonDisabled = true;
this.openLogin(event);
return false;
}
}
ngOnInit() {
this.auth.isAuthenticated.subscribe((authenticated) => {
this.isUserLogged = authenticated;
});
}
async openLogin(ev: any) {
const popover = await this.popoverController.create({
component: OnlyLoggedComponent,
event: ev,
translucent: true,
animated: true,
size: 'auto'
});
await popover.present();
const { role } = await popover.onDidDismiss();
console.log('onDidDismiss resolved with role', role);
}
}
離子版本:6.18.1 角度:13.0.3 節點:16.13.2
我進行了很多搜索,但沒有找到解決方案......有人可以告訴我我做錯了什么嗎?
uj5u.com熱心網友回復:
從您的問題中,我了解到您正在嘗試使用@HostListener指令攔截點擊事件。
實際上,我也無法使用主機偵聽器使這種請求的行為起作用。
在我看來,問題在于stopPropagation模式bubbling阻止了從孩子到父母的事件觸發。
但問題是您正試圖根據某些條件阻止點擊元素本身。
換句話說你需要的正好相反,你需要申請stopPropagation,capturing mode從父母到孩子
我的建議是使用rxjs fromEvent- https://rxjs.dev/api/index/function/fromEvent
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
import { fromEvent, Subscription } from 'rxjs';
@Directive({
selector: '[onlyLogged]'
})
export class OnlyLoggedDirective {
sub = new Subscription();
logged: boolean = true;
constructor(private elRef: ElementRef) {}
ngOnInit() {
const el = this.elRef.nativeElement;
this.sub = fromEvent(el.parentNode, 'click', { capture: true})
.subscribe( (ev: any) => {
if(ev.target == el) { this.checkLogin(ev); }
})
}
checkLogin(ev: any) {
if(!this.logged) {
console.log("user is not logged in", );
ev.stopImmediatePropagation();
this.openLogin(ev);
} else {
console.log("user is logged in");
}
}
openLogin(ev: any) {
console.log('onDidDismiss resolved with role');
}
}
<ion-content [fullscreen]="true">
<div onlyLogged (click)="run()">click on me</div>
</ion-content>
run() {
console.log("This click has to be prevented, when user is not logged in");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/450295.html
