这是一个最小的例子。我正在尝试显示一个文本区域,并将焦点设置到该区域。没用如果文本区域可见,则焦点工作良好,但在使文本区域可见后,它将失去焦点。为什么?
<div class="posts">
<div class="post">
<textarea #textarea1 [(ngModel)]="text" class="comment-text" name="text"></textarea>
</div>
<button (click)="textarea1.focus()">SetFocus on the first textarea</button>
<br><br>
<div class="post">
<textarea #textarea2 [(ngModel)]="text" [hidden]="!show" class="comment-text" name="text"></textarea>
</div>
<button (click)="show = !show; textarea2.focus()">SetFocus on the second textarea</button>
</div>
答案 0 :(得分:1)
当hidden属性变为false时,focus()命令无法获取文本区域。 只需使用一个小的setTimeout()就可以解决该问题。
https://stackblitz.com/edit/so-01-angular-4tl2u
showAndFocus(elem) {
this.show = !this.show;
setTimeout(() => {
elem.focus();
},10);
}
<button (click)="showAndFocus(textarea2)">SetFocus on the second textarea</button>
答案 1 :(得分:0)
<div class="posts">
<div class="post">
<textarea #textarea1 [(ngModel)]="text" class="comment-text" name="text"></textarea>
</div>
<button (click)="textarea1.focus() ; textarea2.focus=false">SetFocus on the first textarea</button>
<br><br>
<div class="post">
<textarea #textarea2 [(ngModel)]="text" [hidden]="!show" class="comment-text" name="text"></textarea>
{{ textarea2.focus() }}
</div>
<button (click)= "show = !show " >SetFocus on the second textarea</button>
</div>