【问题标题】:Angular DOM is not updatedAngular DOM 未更新
【发布时间】:2020-03-28 11:31:03
【问题描述】:

我尝试用我的滑块创建效果(我使用 Swiper)。

我可以在 move 事件中检索滑块的确切位置,我可以在 console.log 中看到该位置实时更新,但是这些更改没有反映在 DOM 中,我不明白为什么......

这是我的组件:

ngOnInit(){

    this.swiper = new Swiper(containerSelector, {
      width:375,
      slidesPerView: 1,
      initialSlide: 1
    });

  }

  ngAfterViewInit(){
    this.swiper.on('setTranslate', function(translate){
      this.currentTranslate = Math.abs(translate);
      this.windowWidth = window.screen.width;
      if(this.currentTranslate == this.windowWidth){
        // Home view
        console.log("middle !");
        this.scaleYahLogo = 1;
        this.scaleYahIcn = 0;
        this.opacityChatsGrey = 1;
        this.opacityChatsColor = 0;
        this.opacityProfileGrey = 1;
        this.opacityProfileColor = 0;
        this.headerPosi = 0;
      } 
      else if(this.currentTranslate < this.windowWidth){
        // Profile view
        console.log("left !");
        this.scaleYahLogo = 0;
        this.scaleYahIcn = 1;
        this.opacityChatsGrey = 0;
        this.opacityChatsColor = 1;
        this.opacityProfileGrey = 0;
        this.opacityProfileColor = 1;
        this.headerPosi = 0;
      }
      else if(this.currentTranslate > this.windowWidth){
        // Chats view
        console.log("right !");
        this.scaleYahLogo = 0;
        this.scaleYahIcn = 1;
        this.opacityChatsGrey = 0;
        this.opacityChatsColor = 1;
        this.opacityProfileGrey = 0;
        this.opacityProfileColor = 1;
        this.headerPosi = 0;
      }
    }) 
  }

我做错了什么?我从昨天开始就在挣扎……

谢谢大家!

【问题讨论】:

    标签: angular ionic-framework swiper


    【解决方案1】:

    Javascript 中的this 关键字function() 指的是函数的范围。要使用成员变量,请使用箭头函数。你可以试试下面的

    ngAfterViewInit() {
      this.swiper.on('setTranslate', (translate) => {  // <-- arrow function instead of `function()` construct
        this.currentTranslate = Math.abs(translate);
        this.windowWidth = window.screen.width;
        if (this.currentTranslate == this.windowWidth) {
        .
        .
        .
      })
    }
    

    【讨论】:

      【解决方案2】:

      这是因为您的修改是在 Angular 的更改检测周期之外进行的(使用 on 处理程序)

      使用 ChangeDetectorRef 通知 Angular 您的更改

      import { ChangeDetectorRef } from '@angular/core';
      
      constructor(private cdr: ChangeDetectorRef){}
      
      
      this.swiper.on('setTranslate', (translate) =>{
      
          //Your code here
          this.currentTranslate = Math.abs(translate);
            this.windowWidth = window.screen.width;
            //...
          this.cdr.detectChanges();// Call this method
      });//end translate
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多