Not able to bind change or ngModelChange to ng-select using addEventListener

56 views Asked by At

I have a formgroup with multiple controls like input, ng-selects etc. Now, I want to get notified whenever user changes value of some specific inputs and ng-selects. I don't want to do it via valueChanges subscribe due to some reasons.

For sample scenario, I have created one input and one ng-select control and binding change event to input and ng-select using addEventListener. It's working fine for inputs but not for ng-selects. I have tried changing the event to ngModelChange for ng-select but still it's not working.

Also, I wanted to pick the common elements using viewchildren via common class abc but the element list is not coming when picking via class.

Below is the code. HTML

<form action="" [formGroup]="doomsForm">
  <input class="abc" type="text" placeholder="Enter Name" formControlName="name"
  #qwe />
  <ng-select
    [items]="ageArr"
    formControlName="age"
    placeholder="Enter Age"
    #qwe
    class="abc"
  ></ng-select>
</form>

TS Code

@ViewChildren('qwe', { read: ElementRef }) commonElements!: QueryList<ElementRef>;
@ViewChildren('.abc', { read: ElementRef }) commonElements!: QueryList<ElementRef>; 
// above line for view children  using .abc class is not working

ngAfterViewInit() {
  this.ValueChange();
}
ValueChange() {
const elements = this.commonElements.toArray();

// Add event listeners dynamically
elements.forEach((element, index) => {
  if (element.nativeElement.tagName === 'INPUT') {
    element.nativeElement.addEventListener('change', () => {
      // Handle change for input or ng-select elements
      this.onInputChange(element.nativeElement.value, index);
    });
  } else if (element.nativeElement.tagName === 'NG-SELECT') {
    element.nativeElement.addEventListener('ngModelChange', () => {
      this.onSelectChange(element.nativeElement, index);
      // }
    });
  }
});
}
onInputChange(value: string, index: number) {
  console.log(`Input ${index + 1} value changed:`, value);
}

onSelectChange(element: any, index: number) {
  console.log(`Ng-select ${index + 1} value changed:`, element.selectedItems);
}
0

There are 0 answers