Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

272
Visualizações
Give dynamic id Angular2 Binds

My JavaScript:

 this.items = [
            {name: 'Amsterdam1', id: '1'},
            {name: 'Amsterdam2', id: '2'},
            {name: 'Amsterdam3', id: '3'}
        ];

My HTML:

<ul>
  <li *ngFor="#item of items" id={{item.id}}>
    {{ item.name}}
  </li>
</ul>

I want to assign a dynamic id to each element, but can't get it to work. The name is showing up but the id is not.

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

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

over 4 years ago · Santiago Trujillo Relatório

0

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.

over 4 years ago · Santiago Trujillo Relatório

0

<ul>
 <li *ngFor="#item of items" attr.id={{item.name}}>
  {{ item.name}}
 </li>
</ul>

This should work (worked for me on angular2).

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda