HTML输入的命名 [英] Naming of HTML inputs
问题描述
在Angular 2中为HTML控件命名的推荐做法是:<input id="abc" name="abc" />
? Id
对于<label for="abc">...</label>
之类的东西是必需的,而Angular绑定需要设置name
. id
和name
不能/不应该总是相同的任何原因?
What is the recommended practice in Angular 2 for naming HTML controls: <input id="abc" name="abc" />
? Id
is necessary for things like <label for="abc">...</label>
, while Angular binding needs name
to be set. Any reason why id
and name
couldn't/shouldn't always be the same?
当您一次使用多个组件(例如,在列表中)或父级和子级组件设置了相同的id
/name
时,情况如何. Angular可能正确处理name
,但是如何防止与id
发生冲突?
How about when you have a component used more than once (e.g. in a list) or a parent and child component have the same id
/name
set. Angular might handle name
correctly, but how do you prevent collisions with the id
?
推荐答案
如果您正在字符串上重用组件,则可能正在使用一组组件,并且可以使id取决于您的*ngFor
的let i = index;
像这样自定义id元素:
If you are reusing components on a string it is likely that you are using a set of them and can make the id dependent on your *ngFor
's let i = index;
to customize the id element like so:
<div *ngFor="let item of items; let i = index">
<p [id]="i + 'p'">{{item}}<p>
</div>
将产生'0p','1p','2p'等的ID.
Will yield IDs of '0p', '1p', '2p', etc.
否则,您可以将要绑定到ID的内容作为组件的输入
Otherwise you could pass something you want bound to the ID as an input to a component
<test-component [myId]="variableFromParent"></test-component>
和测试组件将具有例如:
and the test component would have, for instance:
<div id="{{myId}}"></div>
您可以在plunker中四处乱逛,看看自己喜欢什么,这是一个起点: http: //plnkr.co/edit/UUGtMib8a2wCVP520uD1?p=preview
You can muck around in plunker and see what you like, here's a starting point: http://plnkr.co/edit/UUGtMib8a2wCVP520uD1?p=preview
这篇关于HTML输入的命名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!