【问题标题】:Focus on unhidden object专注于未隐藏的对象
【发布时间】:2020-03-21 21:50:08
【问题描述】:

所以,我找到了以下示例,说明如何在 Angular 中关注对象。

https://codeburst.io/focusing-on-form-elements-the-angular-way-e9a78725c04f

只要文本框始终可见,它就可以正常工作。我通过更改布尔变量尝试了 hidden 和 *ngIf ,它总是找不到对象。

有谁知道在显示对象后我可能需要做些什么来设置焦点?

谢谢

【问题讨论】:

  • 如果您以ViewChild 的方式执行此操作,则 ngIf 会从 DOM 中删除该元素,听起来您只是错过了对 markForCheck()detectChanges()changeDetectorRef 调用之后您切换可见性布尔以获取参考。或者总是可以做香草 JS 的方式。
  • 这最终成为了答案。我认为detectChanges 是他们以前的地方,但事实并非如此。谢谢!

标签: angular


【解决方案1】:

请记住,您需要让 Angular 喘口气来检查它是否可见或不是输入。你使用 setTimeout() 来呼吸

想象一下你有这样的表格

<form [formGroup]="form">
  <input type="checkbox" [ngModel]="check" 
  (ngModelChange)="check=$event;focus()"
  [ngModelOptions]="{standalone: true}"
  >Surname visible
  <input formControlName="name">
  <input #surnameControl *ngIf="check" formControlName="surname">

  </form>

在您的 .ts 中

  @ViewChild('surnameControl',{static:false}) control:ElementRef
  focus()
  {
    //outside setTimeout this.control is undefined
    setTimeout(()=>{
      this.control.nativeElement.focus()
    })
  }

a simple example

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-18
    • 1970-01-01
    • 2020-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多