https://stackblitz.com/edit/angular-ivy-jhuygq
1 2
| <div id="00">toto</div>
<div id="01">toto</div> |
1 2 3 4 5 6 7 8 9 10 11 12
| ngOnInit() {
let app: HTMLElement;
for (let i = 0; i < 2; i++) {
const test: string = '0' + i.toString();
app = document.getElementById(test);
app.addEventListener('click', this.handleClick);
}
}
handleClick() {
console.log('click');
} |
j'ai mis une boucle qui va de 0 à 1
comme j'ai mis 2 element html dans la vue
il n'y a pas d'erreur
tu peux mettre une protection
if (app) { app.addEventListener('click', this.handleClick); }
** mais sache que ce n'est pas une bonne pratique d'utiliser : document.getElementById(
c'est du pure JavaScript, tu n'utuilses pas angular
1 2
| <div (click)="handleClick(1)">toto</div>
<div (click)="handleClick(2)">tutu</div> |
ou dans une boucle for :
1 2 3 4 5 6 7
| <li *ngFor="let book of bookList; let index = index;">
<span (click)="handleClick(index)">{{ book.name }}</span>
// ou en passant id :
<span (click)="handleClick(book.id)">{{ book.name }}</span>
</li> |
Partager