Angular 单击“在文本区域设置焦点角度5” 帖子内容 评论 帖子内容 评论 ...
我想在“a”点击时设置文本区域的焦点。谁能帮帮我吗。我正在使用angular 5您可以使用@ViewChild装饰器。文档: 您需要为输入元素指定一个名称,并连接一个单击事件Angular 单击“在文本区域设置焦点角度5” 帖子内容 评论 帖子内容 评论 ...,angular,angular5,Angular,Angular5,我想在“a”点击时设置文本区域的焦点。谁能帮帮我吗。我正在使用angular 5您可以使用@ViewChild装饰器。文档: 您需要为输入元素指定一个名称,并连接一个单击事件 <div class="posts"> <div class="post"> <div>post content</div> <a class="comment">Comment</a> <textar
<div class="posts">
<div class="post">
<div>post content</div>
<a class="comment">Comment</a>
<textarea [(ngModel)]= "model.text" class="comment-text" name="text"></textarea>
</div>
<div class="post">
<div>post content</div>
<a class="comment">Comment</a>
<textarea [(ngModel)]= "model.text" class="comment-text" name="text"></textarea>
</div>
</div>
...
注意:当触发ngAfterViewInit
事件时,inputElement
变量将首先可用
更新问题导致的更新:要处理多个元素,您需要使用@ViewChildren文档:
在上面给出的代码示例中,我将把冗余代码制作成它自己的组件,以封装重复的功能。这里您可以循环
export class App implements AfterViewInit {
@ViewChild("inputToFocus") inputElement: ElementRef;
focusInput() {
this.inputElement.nativeElement.focus()
}
像这样使用ViewChildren
和QueryList
读取元素
import { Component, ViewChildren, QueryList, ElementRef } from '@angular/core';
@ViewChildren("txtArea") textAreas:QueryList<ElementRef>;
更新上面的代码将与
帖子的数组一起使用
。因此,我们不需要像#txtArea1、#txtArea2等那样硬编码id。
请在这里查看如果您正在迭代
,您可以传递索引
(此处i
)以从下面的查询列表获取相应的文本区域
引用
doSomething(index: number) {
this.textAreas.find((item, idx) => {
return idx === index;
}).nativeElement.focus();
}
如果使用模板变量,则可以直接从HTML文件中的标记设置焦点。您可以在(单击)
方法中引用它。这样,无需通过代码访问DOM,它保留在HTML文件中,便于调试:
HTML
<a class="comment" (click)="textAreas.toArray()[i].nativeElement.focus()">Comment</a>
。。。
在第一个文本区域设置焦点
...
在第二个文本区域设置焦点
...
只需使用querySelector或ViewChild并对结果元素调用.focus()。使用ViewChildren
和QueryList
即可实现此目的。检查我的回答谢谢。如果我有多个textarea和“a”,那么我如何才能做到这一点。谢谢Vega,他的就是我的情况。我喜欢将它保存在HTML中的想法。最好的!
doSomething(index: number) {
this.textAreas.find((item, idx) => {
return idx === index;
}).nativeElement.focus();
}
<a class="comment" (click)="textAreas.toArray()[i].nativeElement.focus()">Comment</a>
...
<textarea #textarea1 [(ngModel)]="text" class="comment-text" name="text"></textarea>
<button (click)="textarea1.focus()">SetFocus on the first textarea</button>
...
<textarea #textarea2 [(ngModel)]="text" class="comment-text" name="text"></textarea>
<button (click)="textarea2.focus()">SetFocus on the second textarea</button>
...