如何使用formcomtrol捕获选择元素的绑定事件-ReactiveFomrModule -Angular 4

时间:2018-10-22 11:56:19

标签: angular angular4-forms

我正在使用reactformformmodule并为select标签创建了一个formcontrol。 在页面加载时,我正在从后端获取数据,并使用patchvalue将其绑定到selectformcontrol。但是这样做时,不会触发select的change事件。

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

我的应用程序中有很多选择标签,因此无法捕获每个selectformcontrol的valuechange。

我想通过创建一个指令并向其添加hostlistener来概括如下

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

和我在课堂上的代码

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

但是当使用表单控件.patchValue修补数据时,不会触发此onChange,当我手动选择该选项时,将触发该onChange。

我想捕获一个事件,该事件在选择标记中修补数据时触发。

2 个答案:

答案 0 :(得分:1)

所以分享一些示例代码来满足您的要求对我有用:

指令

 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');
        }

    }

模块(您要在其中使用)

declarations: [
    SelectDirective
  ]

答案 1 :(得分:0)

太好了!我在这里测试一些例子! 在您的组件中:

  testForm:FormGroup;

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

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

在html中:

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

尝试一下,告诉我是否有效!! 谢谢!