[英]Write arbitrary html tag attribute based on *ngFor 'first' variable?
I have a component which uses *ngFor to display a list of widgets/DIVs, each of which contains a textarea element. 我有一个使用* ngFor来显示小部件/ DIV列表的组件,每个小部件/ DIV都包含一个textarea元素。
I want to set the focus on the first textarea to appear from this list of widgets/DIVs. 我想把焦点放在第一个textarea上,从这个小部件/ DIV列表中显示出来。
Can I use the 'first' variable of the ngFor directive to write arbitrary html? 我可以使用ngFor指令的'first'变量来编写任意html吗? In my case, I would like to add the 'autofocus' tag/attribute into the first textarea element my component writes:
在我的例子中,我想将'autofocus'标签/属性添加到我的组件写入的第一个textarea元素中:
eg <textarea autofocus></textarea>
例如
<textarea autofocus></textarea>
I put a sample plunkr here that works, but it uses the ngAfterViewInit() method, which seems clunky to me when my component knows which element is first in the list: https://embed.plnkr.co/a3zXZd9WBFNTj6yu1oU6/ 我在这里放了一个样本plunkr,但它使用了ngAfterViewInit()方法,当我的组件知道列表中的第一个元素时,这对我来说似乎很笨: https : //embed.plnkr.co/a3zXZd9WBFNTj6yu1oU6/
Thank you. 谢谢。
You can just bind first
local variable to autofocus: 您可以将
first
局部变量绑定到自动对焦:
<div *ngFor="let name of NAME_LIST; let first = first;">
{{name}}<br />
<textarea [autofocus]="first"></textarea> <br /><br />
</div>
you can use index variable : 你可以使用索引变量:
<div *ngFor="let name of NAME_LIST; let i = index;">
{{name}}<br />
<textarea [autofocus]="i === 0"></textarea> <br /><br />
</div>
You can use setAttribute() method as below, 你可以使用如下的setAttribute()方法,
HTML will be as HTML将如此
<div>
<h2>How to set focus on first TEXTAREA element from list?</h2>
</div>
<div *ngFor="let name of NAME_LIST">
{{name}}<br />{{first}}
<textarea ></textarea><br /><br />
</div>
<span> {{getFocused()}} </span>
Typescript method: 打字稿方法:
getFocused(){
document.querySelectorAll('textarea')[0].setAttribute("autofocus", "true");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.