Search code examples
angularangular4-forms

How to capture bind event of select element using formcomtrol - ReactiveFomrModule -Angular 4


I am using reactiveformmodule and has created a formcontrol for select tag. On load of the page I am fetching data from backend and binding it using patchvalue to the selectformcontrol. But in doing this the change event of select is not fired.

 in .html
 <select id="businessType" formControlName="businessType">
                    <option value="-1">Business type</option>
                    <option *ngFor="let business of businessTypes; let i=index;" [value]="i">{{business.b_type}}</option>
                </select>

 in .ts
 this.formGroupObject.patchValue({
        'businessType': 0 //"0" is coming from backend
    })

I have lot of select tags across my application, so cannot capture valuechange for each selectformcontrol.

I wanted to generalize by creating a directive and adding hostlistener to it like below

@Directive({
selector: 'select',
})

and my code inside class

@HostListener('change', ['$event'])
onChange(event) {
    //do something
}

But this onChange is not fired when data is patched using form control .patchValue, when I manually select option then this is triggered.

I want to capture an event which gets triggered when the data is patched in select tag.


Solution

  • So sharing some sample code to meet your requirement which worked for me :

    Directive

     import { Directive, ElementRef, HostListener } from '@angular/core';
    
        @Directive({
            selector: 'select'
        })
        export class SelectDirective {
            constructor(private el: ElementRef) { 
            }
    
            @HostListener('change', ['$event'])
            onChange(event) {
                console.log(event);
            }
    
            @HostListener('ngModelChange') onNgModelChange() {
                console.log('ngModelChange');
            }
    
        }
    

    Module (In which you want to use)

    declarations: [
        SelectDirective
      ]