问题
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.
回答1:
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
]
回答2:
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!
来源:https://stackoverflow.com/questions/52928773/how-to-capture-bind-event-of-select-element-using-formcomtrol-reactivefomrmodu