Naming of HTML inputs

旧城冷巷雨未停 提交于 2019-12-25 04:34:20

问题


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?

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?


回答1:


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>

Will yield IDs of '0p', '1p', '2p', etc.

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>

You can muck around in plunker and see what you like, here's a starting point: http://plnkr.co/edit/UUGtMib8a2wCVP520uD1?p=preview



来源:https://stackoverflow.com/questions/40556487/naming-of-html-inputs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!