Naming of HTML inputs

2019-09-07 01:50发布

问题:

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