代码之家  ›  专栏  ›  技术社区  ›  John Montgomery

在元素通过ngif出现后聚焦该元素

  •  1
  • John Montgomery  · 技术社区  · 8 年前

    我有一个按钮,当点击时,它会被一个输入字段和一个确认按钮替换,然后当输入完成后,它会再次被原始按钮替换。当这种情况发生时,我希望它在原始按钮出现后聚焦(一些用户要求更好地支持选项卡导航),但我似乎不能让它一直这样做。我能做的最好的事情是:

    // component.html
    <button #durationButton *ngIf="!enteringDuration" (click)="enterDuration()">Enter Duration</button>
    <ng-container *ngIf="enteringDuration">
        <input type="number" [(ngModel)]="duration" (keyup.enter)="setDuration()">
        <button (click)="setDuration()">&#10003;</button>
    </ng-container>
    
    // component.ts
    @ViewChild("durationButton") durationButton: ElementRef
    duration: number
    enteringDuration = false
    shouldFocusDurationButton = false
    
    ngAfterContentChecked () {
        if (this.shouldFocusDurationButton && this.durationButton) {
            this.shouldFocusDurationButton = false
            this.durationButton.nativeElement.focus()
        }
    }
    
    enterDuration () {
        this.enteringDuration = true
    }
    setDuration () {
        this.enteringDuration = false
        this.shouldFocusDurationButton = true
    }
    

    如果我单击或按确认按钮上的Enter键,焦点一出现就移动到原始按钮,但是如果我在输入字段中按Enter键,按钮就会出现,但由于某种原因,直到我移动鼠标,它才获得焦点。我如何使它立即对两者都有效?

    2 回复  |  直到 8 年前
        1
  •  1
  •   ConnorsFan    8 年前

    ViewChildren QueryList.changes QueryList this stackblitz

    import { Component, ViewChildren, ElementRef, AfterViewInit, QueryList } from '@angular/core';
    ...
    
    export class AppComponent implements AfterViewInit {
    
      @ViewChildren("durationButton") durationButton: QueryList<ElementRef>;
    
      enteringDuration = false
    
      ngAfterViewInit() {
        this.durationButton.changes.subscribe((button) => {
          if (button.length > 0) {
            button.first.nativeElement.focus();
          }
        });
      }
    
      enterDuration() {
        this.enteringDuration = true
      }
    
      setDuration() {
        this.enteringDuration = false
      }
    }
    
        2
  •  0
  •   DeborahK    8 年前
    推荐文章