*ngIf不检测swiper.js (slideChange)事件的变量变化,但检测swiperRef. js.slid



我将一个包含照片url的对象数组传递给swiper容器,对于未经验证的照片,我显示了一个文本,每次更换幻灯片时,我都要检查照片验证状态变量变为true或false但是dom没有更新,即使我检查它显示

ng-reflect-ng-if :'true;

但是我必须滚动到特定的幻灯片用户点击特定的缩略图

对于我使用的

this.photoPopupSlider.swiperRef.slideTo(RowIndex, sliderSpeed);

此时onSlidChange事件触发正确更新dom

my component.html👇

<div style="padding: 0">
<swiper
[config]="sliderConfig"
class="sliderBox"
[pagination]="false"
(slideChange)="onSlideChange($event)"
#photoPopupSlider
>
<ng-template swiperSlide *ngFor="let pic of myPhotos">
<div
class="slide_wrap"
style="height: 68vh; background: #f3f4f9"
>
<img
[src]="pic.image"
class="slide_img"
style="height: auto; width: auto; max-width: 100%"
/>
</div>
</ng-template>
</swiper>
<span
id="photo_under_verification"
*ngIf="underVerification"
class="ph_uv"
>Photo under verification</span
>
</div>

我的组件。Ts文件👇

underVerification = false;
onSlideChange([swiper]: any) {
const index = swiper.activeIndex;
this._ps.sliderIndex = index;
this.sliderIndex = index;
console.log("sliderChanged", this.sliderIndex);
const photoShowingInSlider = this.myPhotos[index];
const isPhotoUnderVerification =
photoShowingInSlider?.photostatus == "0" ? true : false;
this.underVerification = isPhotoUnderVerification;
console.log("under", isPhotoUnderVerification);
// const photUnderVerifyMsg = document.getElementById(
//   "photo_under_verification"
// ).style;
// if (isPhotoUnderVerification) photUnderVerifyMsg.display = "inline";
// else photUnderVerifyMsg.display = "none";
}

实际上我能够通过使用document.getElemntById

实现逻辑那些注释的代码行(我认为在angular中这样访问dom是一种不好的方式)

如何用angular的方式实现这个登录(意味着不直接访问dom) ?

好吧,你必须告诉Angular运行变更检测,因为onSlideChange(和其他事件)下的代码运行在

区域之外。

注意,Swiper Angular组件的所有事件都是在NgZone之外发出的为了更好的表现。不要忘记使用ngzone.run或如果您需要在事件中更改视图(例如幻灯片),请使用ChangeDetector处理程序(如slideChange)。

在构造函数中导入ChangeDetectorRef并调用onSlideChange方法中的detectChange方法

this.cd.detectChanges()

下面是工作代码。我只是取了一个随机的stackblitz链接,所以要适应你的swiper版本:https://stackblitz.com/edit/swiper-angular-example-rmgv2b

最新更新