ViewChild和focus() [英] ViewChild and focus()

查看:101
本文介绍了ViewChild和focus()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含文本区域的组件,该区域默认情况下是隐藏的:

I have a component which contains a textarea which is hidden by default :

<div class="action ui-g-2" (click)="toggleEditable()">edit</div>
<textarea [hidden]="!whyModel.inEdition" #myname id="textBox_{{whyModel.id}}" pInputTextarea focus="true" [(ngModel)]="whyModel.description"></textarea>

当我单击"edit" div时,我想显示文本区域并对其进行关注:

When I click on the "edit" div I want to show the textarea and put focus on it :

@ViewChild('myname') input: ElementRef;
...
private toggleEditable(): void {
  this.whyModel.toggleEditable();
  this.input.nativeElement.focus();
}

显示"部分正在工作,但焦点部分没有工作.我想念什么?

The "show" part is working but not the focus part. What do I miss?

推荐答案

仅在运行更改检测时(通常在事件处理程序完成之后),才更新绑定.对于您的用例来说,这太迟了,因为事件处理程序本身已经取决于变更检测的效果.

Bindings are only updated when change detection runs, which is usually after an event handler completed. This is to late for your use case, because the event handler itself depends already on the effect of change detection.

您可以通过调用detectChanges()

constructor(private cdRef:ChangeDetectorRef) {}

@ViewChild('myname') input: ElementRef;
...
private toggleEditable(): void {
  this.whyModel.toggleEditable();
  this.cdRef.detectChanges();
  this.input.nativeElement.focus();
}

这篇关于ViewChild和focus()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆