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

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

问题描述

我有一个包含默认隐藏的 textarea 的组件:

edit

<textarea [hidden]="!whyModel.inEdition" #myname id="textBox_{{whyModel.id}}" pInputTextarea focus="true" [(ngModel)]="whyModel.description"></textarea>

当我点击编辑"div 时,我想显示 textarea 并将焦点放在它上面:

@ViewChild('myname') 输入:ElementRef;...私人切换可编辑():无效{this.whyModel.toggleEditable();this.input.nativeElement.focus();}

显示"部分有效,但焦点部分无效.我想念什么?

解决方案

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

您可以通过调用 detectChanges()

立即(同步)强制执行变更检测

constructor(private cdRef:ChangeDetectorRef) {}@ViewChild('myname') 输入:ElementRef;...私人切换可编辑():无效{this.whyModel.toggleEditable();this.cdRef.detectChanges();this.input.nativeElement.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>

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.

You can enforce change detection immediately (synchronically) by calling 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天全站免登陆