【问题标题】:Set input focus every time inside ng-template每次在 ng-template 中设置输入焦点
【发布时间】:2019-08-17 22:26:39
【问题描述】:

在我的应用程序中,我有一个输入元素,当我单击按钮时它是可见的,当我单击另一个按钮时它是隐藏的。我通过一个简单的 ng-template 实现了这一点。我想在此输入可见时为其设置焦点。我将autofocus 参数设置为输入,但如果我多次切换可见性(输入失去焦点),它就不起作用。我已经尝试了这个SO 问题中描述的替代方案(ViewChildRenderer2),但它也不起作用。

app.component.html

<div *ngIf="!isInputVisible; else inputTemplate">Input goes here after click!</div>

<button (click)="toggleInputVisibility()">Toggle input</button>

<ng-template #inputTemplate>
  <input type="text" autofocus>
</ng-template>

app.component.ts:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  public isInputVisible: boolean = false;

  public toggleInputVisibility(): void {
    this.isInputVisible = !this.isInputVisible;
  }
}

工作stackblitz

【问题讨论】:

    标签: angular


    【解决方案1】:

    基于the description of the autofocus attribute,它应该只关注“页面加载”样式功能,而不是创建/删除内容时。

    @ContentChild 显示在页面上后,您可以将其与this.contentChild.nativeElement.focus() 一起使用。

    您还可以从@ContentChildren 订阅QueryList 以触发焦点 (found here)。

    【讨论】:

      【解决方案2】:

      如果您仍在寻找解决方案,这可能会有所帮助。 我使用@ViewChild 装饰器来获取他的输入元素并将焦点设置在它上面。我在这里使用延迟使其异步。您也可以使用检测更改。

      修改了你的stackblitz

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-12-30
        • 1970-01-01
        • 1970-01-01
        • 2018-06-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多