Give dynamic id Angular2 Binds

后端 未结 4 2076
时光说笑
时光说笑 2021-02-05 03:11

My JavaScript:

 this.items = [
            {name: \'Amsterdam1\', id: \'1\'},
            {name: \'Amsterdam2\', id: \'2\'},
            {name: \'Amsterdam3\', i         


        
相关标签:
4条回答
  • 2021-02-05 03:29

    I found the answer. I can use [attr.id] tag on the 'li' tag.

    0 讨论(0)
  • 2021-02-05 03:41

    the way you said works, Angular 2.0.0.beta.8.

    in this case you can use for example:

    • [id]="item.id"
    • [attr.id]="item.id"
    • id={{item.id}}

           <ul>
            <li *ngFor="#item of items" #elem [id]="item.id">
              {{ item.name}} ID: {{elem.id}}
            </li>
           </ul>
      
           <ul>
            <li *ngFor="#item of items" #elem [attr.id]="item.id">
              {{ item.name}} ID: {{elem.id}}
            </li>
           </ul>
      
           <ul>
            <li *ngFor="#item of items" #elem id={{item.id}}>
              {{ item.name}} ID: {{elem.id}}
            </li>
           </ul>
      

    Plunker

    You can look here for more information in Template syntax.

    https://angular.io/guide/cheatsheet

    0 讨论(0)
  • 2021-02-05 03:43
    <ul>
     <li *ngFor="#item of items" attr.id={{item.name}}>
      {{ item.name}}
     </li>
    </ul>
    

    This should work (worked for me on angular2).

    0 讨论(0)
  • 2021-02-05 03:52

    All the methods provided by @AngelAngel are correct but just to explain why to use [attr.id] posted as answer.

    Angular by default uses property binding. To tell Angular explicitly to use attribute binding, we use instead:

        <ul>
          <li *ngFor="#item of items" #elem [attr.id]="item.id">
            {{ item.name}} ID: {{elem.id}}
          </li>
         </ul>
    

    With attr.id you have to explicitly opt in to attribute binding because attribute binding is expensive. Attributes are reflected in the DOM and changes require for example to check if CSS selectors are registered that match with this attribute set. Property binding is JS only and cheap, therefore the default.

    0 讨论(0)
提交回复
热议问题