代码之家  ›  专栏  ›  技术社区  ›  djain4

如何使用formcomtrol-reactivefomrmodule-angular 4捕获select元素的绑定事件

  •  0
  • djain4  · 技术社区  · 6 年前

    我正在使用reactiveformmodule并为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
        })
    

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

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

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

    我的代码在课堂上

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

    但当使用表单控件修补数据时,不会触发此onchange。patchvalue,当我手动选择选项时,则会触发此onchange。

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

    2 回复  |  直到 6 年前
        1
  •  1
  •   Vishw Patel    6 年前

    因此,共享一些示例代码以满足您的要求,这对我很有用:

    指令

     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
      ]
    
        2
  •  0
  •   Chiien    6 年前

    伟大的!我在这里测试一些例子! 在您的组件中:

      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>
    

    试试看,告诉我是否有效!! 谢谢!

    推荐文章