Michael Kitchell
Michael Kitchell

Reputation: 119

Angular click event not working with array of objects

I have the following HTML:

<div class="options-wrapper">
  <div *ngFor="let option of options" class="option" (click)="selectOption()">
    {{ option.label }}
  </div>
</div>

with the following component class:

import {
  Component,
  ElementRef,
  HostListener,
  Input,
  Output,
  ViewChild,
} from '@angular/core';

@Component({
  selector: 'mdj-select-list',
  templateUrl: './select-list.component.html',
  styleUrls: ['./select-list.component.scss'],
})
export class SelectListComponent {
  @Input()
  options: { label: string, value: string }[] = [];

  selectedOption: string;

  selectOption() {
    console.log('click');
  }
}

  

For some reason, I have to click the div twice in order to make the selectOption() function run. This only seems to happen when I pass in an array of objects. If I pass in an array of strings, it works as expected.

Upvotes: 1

Views: 492

Answers (1)

CCBet
CCBet

Reputation: 426

I replicated your code in a stackblitz instance and it seems that I'm not getting the same behavior that you get. I get logged every click without having to click twice. Check if there is any difference between my code and yours (excepting file names and the fact that I did not add a styles file).

Upvotes: 1

Related Questions