Angular Reactive Form why valueChanges is called before input listener

断了今生、忘了曾经 提交于 2019-12-23 23:15:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!