How to capture bind event of select element using

2019-09-03 15:10发布

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.

2条回答
等我变得足够好
2楼-- · 2019-09-03 15:21

Great! I test some example here! In your component:

  testForm:FormGroup;

  constructor(
    private fb: FormBuilder
  ) {
    this.testForm = this.fb.group({
      select: ['']
    })
  }

  ngOnInit(){
    this.testForm.controls.select.valueChanges.subscribe((select: string) => {
      console.log(select)
    })
  }

And in html:

 <form [formGroup]="testForm">
    <select formControlName="select" placeholder="Selecione">
      <option value="1">Test 1</option>
      <option value="2">Test 2</option>
    </select>
  </form>

Try that and tell me if is working!! Thanks!

查看更多
成全新的幸福
3楼-- · 2019-09-03 15:33

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
  ]
查看更多
登录 后发表回答