如何使用formcomtrol捕获选择元素的绑定事件-ReactiveFomrModule -Angular 4 [英] How to capture bind event of select element using formcomtrol - ReactiveFomrModule -Angular 4
问题描述
我正在使用reactformmodule,并为select标签创建了一个formcontrol.在页面加载时,我正在从后端获取数据,并使用patchvalue将其绑定到selectformcontrol.但是这样做时,不会触发select的change事件.
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
})
我的应用程序中有很多选择标签,因此无法捕获每个selectform控件的值更改.
I have lot of select tags across my application, so cannot capture valuechange for each selectformcontrol.
我想通过创建一个指令并向其添加hostlistener来概括如下
I wanted to generalize by creating a directive and adding hostlistener to it like below
@Directive({
selector: 'select',
})
和我在课堂上的代码
@HostListener('change', ['$event'])
onChange(event) {
//do something
}
但是当使用表单控件.patchValue修补数据时,不会触发此onChange,当我手动选择该选项时,将触发此onChange.
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.
推荐答案
因此,分享一些示例代码以满足您的要求,这些示例对我有用:
So sharing some sample code to meet your requirement which worked for me :
指令
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
]
这篇关于如何使用formcomtrol捕获选择元素的绑定事件-ReactiveFomrModule -Angular 4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!