gpt4 book ai didi

angular - 通过 ngIf 出现后聚焦元素

转载 作者:行者123 更新时间:2023-12-01 13:18:58 26 4
gpt4 key购买 nike

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

// 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 按钮会出现,但由于某种原因,在我移动鼠标之前它不会获得焦点.我如何让它立即对两者都起作用?

最佳答案

您可以使用 ViewChildrenQueryList.changes当按钮被添加到 View 或从 View 中删除时要通知的事件。如果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.setFocus(); // If the button is already present...
this.durationButton.changes.subscribe(() => {
this.setFocus();
});
}

setFocus() {
if (this.durationButton.length > 0) {
this.durationButton.first.nativeElement.focus();
}
}

enterDuration() {
this.enteringDuration = true
}

setDuration() {
this.enteringDuration = false
}
}

关于angular - 通过 ngIf 出现后聚焦元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51566012/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com