代码之家  ›  专栏  ›  技术社区  ›  Manzur Khan

角度:当元素在ngif中可见时触发事件

  •  3
  • Manzur Khan  · 技术社区  · 7 年前

    我在ngif中有一些div,我只想知道特定的div是否是现在可见/活动的div,比如focus(它不工作)之类的事件触发器,或者其他什么,对于这个事件,我将设置一个变量或其他什么。

    <div *ngIf="test === true" (focus)="myVariable = true">
    </div>
    
    3 回复  |  直到 6 年前
        1
  •  1
  •   Maryannah    7 年前

    触发更改检测后,您的div将呈现并可见。当检测到更改时,将再次运行整个生命周期。

    如果你想运行某个东西,你应该钩住生命周期中的某个事件。我建议 AfterViewInit .

    既然你知道怎么做,让我们看看你该怎么做。

    在您的例子中,应该使用模板引用创建div。这将允许您拥有对元素的引用,并使您能够检查显示或隐藏哪个div。

    Here is a stackblitz 这向您展示了它的工作原理,下面是代码:

    import { Component, ViewChildren, QueryList, ElementRef } from '@angular/core';
    
    @Component({
      selector: 'my-app',
      template: `
      <div *ngFor="let item of [0, 1, 2, 3, 4, 5]; let i = index">
        <span *ngIf="i === show" #shownDiv [id]="'div-' + i">{{ item }}</span>
      </div>
      `
    })
    export class AppComponent {
      name = 'Angular 6';
      show = 0;
    
      @ViewChildren('shownDiv') divs: QueryList<ElementRef>;
    
      ngOnInit() {
        setInterval(() => {
          this.show++;
          if (this.show > 5) {
            this.show = 0;
          }
        }, 1000);
      }
    
      ngAfterViewChecked() {
        let shown = this.divs.find(div => !!div);
        console.log('DIV shown is ' + (shown.nativeElement as HTMLSpanElement).id);
        // Now that you know which div is shown, you can run whatever piece of code you want
      }
    }
    
        2
  •  1
  •   Rachit Shroff    7 年前

    这可能是一个可行的办法。它可能不是最好的,但会起作用。

    在HTML文件中,

    <div *ngIf="show()"> </div>
    

    在组件ts文件中,

    show(){
      if(test){ //condition for showing the div
        myVariable = true; 
        return true;
      }
      else
        return false;
    }
    
        3
  •  1
  •   Cameron Burger    6 年前

    我想以拉希特的回答为基础。

    <div *ngIf="test"><ng-container *ngIf="runShow && show()"></ng-container></div>

    在组件中

    this.runShow = true;
    
    //show always returns true.
    show() {
      //Return if not running. Shouldn't be needed as runShow proceeds show in the template.
      if(!this.runShow) {
        return true;
      }
      //Do modifications...
    
      this.runShow = false;
      return true;
    

    show() this.runShow 以某种东西为基础)。一个重要的问题是直到 this.runShow == false ,这将在组件每次检测到更改时运行,不多也不少。 我们将show()放在它自己的ng容器中,这样它就不会影响dom,并在呈现测试之后运行。

    推荐文章