簡體   English   中英

在 Angular2 中的 setTimeout 之后從 Viewchild 元素中刪除類

[英]Remove class from Viewchild Element after setTimeout in Angular2

嗨,我想從兩個元素中刪除一些類,但我的代碼沒有任何反應。

我的html

<div class="d-flex ml-auto align-items-center animated fadeInRight faster" #outgoing>
  ...
</div>
<div class="d-flex ml-auto align-items-center animated fadeInLeft faster" #incoming>
  ...
</div>

在我的組件中,我嘗試在一秒鍾后從元素中移除animated fadeInLeftfaster的類。

export class TestComponent implements OnInit {

  @ViewChild('outgoing', {static: false}) outgoingEl: ElementRef;
  @ViewChild('incoming', {static: false}) incomingEl: ElementRef;


  constructor(private renderer: Renderer2) {
  }


  ngOnInit() {
      setTimeout(() => {
        this.renderer.removeClass(this.outgoingEl.nativeElement, 'animated');
        this.renderer.removeClass(this.outgoingEl.nativeElement, 'fadeInRight');
        this.renderer.removeClass(this.outgoingEl.nativeElement, 'faster');

        this.renderer.removeClass(this.incomingEl.nativeElement, 'animated');
        this.renderer.removeClass(this.incomingEl.nativeElement, 'fadeInRight');
        this.renderer.removeClass(this.incomingEl.nativeElement, 'faster');
      }, 1000);
    });
  }
}

我究竟做錯了什么? 在 Chrome Dev Tools 中檢查元素時,類不會被刪除。

不要打擾渲染器,使用ngClass

<div class="d-flex ml-auto align-items-center" [ngClass]="outgoingClasses">
  ...
</div>
<div class="d-flex ml-auto align-items-center" [ngClass]="incomingClasses">
  ...
</div>


  outgoingClasses = { 'animated': true, 'fadeInRight': true, 'faster': true }
  incomingClasses = { 'animated': true, 'fadeInLeft': true, 'faster': true }
  ngOnInit() {
      setTimeout(() => {
        this.outgoingClasses = null;
        this.incomingClasses = null;
      }, 1000);
    });
  }

你可以定義變量,如:

outgoingClasses = 'animated fadeInRight faster'

如果這樣可以完成工作,但是如果您願意,您可以在對象結構中添加/刪除單個類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM