问题
what's the order of events in case I have a reactive form and some directives with hosteListener on keyup, keydown, keypress, input, etc?
I'm creating a reactive form with an input text and a directive that take the input and uppercase it:
@HostListener('input')
onInput() {
if (this.uppercase) {
this.el.nativeElement.value = this.el.nativeElement.value.toUpperCase();
}
}
But the method valueChanges of the form is called before the directive, so the value in the model is still lowercase.
Thanks!
回答1:
This took me a while, but finally I managed to crack it. Basically, I had to take over the bridge between the DOM and the model. Angular does this for you unless you implement ControlValueAccessor for your Control/Directive. That way, you are in charge of change the model (and thus firing the listeners to valueChanges) whenever you see fit:
export const MASK_CONTROL_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => MaskDirective),
multi: true
};
@Directive({
selector: "[testMask]",
providers: [MASK_CONTROL_VALUE_ACCESSOR]
})
export class MaskDirective implements ControlValueAccessor {
private onChange;
private nativeElement;
constructor(private element: ElementRef) {
this.nativeElement = this.element.nativeElement;
}
registerOnChange(fn: any): void {
this.onChange = fn;
}
registerOnTouched(fn: any): void {
}
setDisabledState(isDisabled: boolean): void {
this.nativeElement.disabled = isDisabled;
}
writeValue(newValue) {
newValue = newValue == null ? "" : newValue;
this.nativeElement.value = newValue;
}
@HostListener("input", ["$event"])
onInput(event: KeyboardEvent) {
/*DO YOUR STUFF HERE*/
// Call onChange to fire the valueChanged listeners
this.onChange(newValue);
}
}
来源:https://stackoverflow.com/questions/50628704/angular-reactive-form-why-valuechanges-is-called-before-input-listener