1

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.

4
  • 2
    how about if you wrap your option.label in a proper HTML element, like a ul>li? Why do you want the text to be inside the div? seems like a bad HTML structure Commented Aug 4, 2022 at 21:13
  • @Andres2142 that doesn't make any difference with my original issue. Commented Aug 4, 2022 at 21:22
  • 1
    The event should be indexed. It should be one level down in your HTML structure pointing the element from the list in the DOM not to the whole list Commented Aug 4, 2022 at 21:33
  • 1
    please add the code where you set the input data Commented Aug 5, 2022 at 4:17

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.