Search code examples
angulartypescriptangular-directiveangular-formsangular-ngmodel

Angular 11 Accessing template driven model in a directive


In Angular 8.2 I have a currency directive that formats currency fields for users and works like this perfectly:

<input [(ngModel)]="currentEmployment.monthlyIncome" currency>
@Directive({
  selector: '[ngModel][currency]',
  providers: [CurrencyPipe, NgModel],
})
export class CurrencyDirective implements OnDestroy {
  // tracking
  private focused: boolean = false;
  private modelSubscription: Subscription;

  // fraction size
  @Input() size: number = 2;
  // positive only
  @Input() positiveOnly: boolean = false;

  // model update
  @Output() ngModelChange: EventEmitter<any> = new EventEmitter();

  constructor(
    private renderer: Renderer2,
    private el: ElementRef,
    private currencyPipe: CurrencyPipe,
    private model: NgModel
  ) {
    // set mobile keyboard to numpad
    this.renderer.setAttribute(this.el.nativeElement, 'pattern', 'd*');
    // input needs to be text when formatted
    this.renderer.setAttribute(this.el.nativeElement, 'type', 'text');

    // format when model is changed from somewhere else
    this.modelSubscription = this.model.valueChanges.subscribe(value => {
      // dont format while user is editing directly
      if (!this.focused) {
        this.setViewModel(this.currencyPipe.transform(value, this.size));
      }
    });
  }

  ngOnDestroy() {
    // unsubscribe from model subscription
    this.modelSubscription.unsubscribe();
  }

  @HostListener('focus')
  focus() {
    // user is editing, disable formating
    this.focused = true;
    // needs to be type number when unformatted
    this.renderer.setAttribute(this.el.nativeElement, 'type', 'number');
    // set the view model to raw data value
    this.setViewModel(this.model.value);

    // select all in input for easy editing
    $(this.el.nativeElement)
      .one('mouseup', event => {
        event.preventDefault();
      })
      .select();
  }

  @HostListener('blur')
  onBlur() {
    // prepare model value
    let newValue = Number(this.model.value);

    // get absolute value if only positive values are allowed
    if (this.positiveOnly) {
      newValue = Math.abs(this.model.value);
    }

    // emit model change before clearing this.focused
    this.ngModelChange.emit(newValue);
    // input needs to be text when formatted
    this.renderer.setAttribute(this.el.nativeElement, 'type', 'text');
    // format view model
    this.setViewModel(this.currencyPipe.transform(newValue, this.size));
    // clear user focus
    this.focused = false;
  }

  private setViewModel(value: any = null): void {
    if (value !== null) {
      this.el.nativeElement.value = value;
    }
  }
}

however when updating to Angular 11.2 I get:

  • no errors
  • this.model.value is always null
  • this.model.valueChanges.subscribe never fires

is there some configuration problem or does model work differently now?


Solution

  • Turns out I just needed to remove NgModel from providers. Angular 9 | ngModel Provider in Directive not working as expected

    I don't totally understand why this works differently but this solved it:

    @Directive({
      selector: '[ngModel][currency]',
      providers: [CurrencyPipe],
    })
    export class CurrencyDirective implements OnDestroy {
      // tracking
      private focused: boolean = false;
      private modelSubscription: Subscription;
    
      // fraction size
      @Input() size: number = 2;
      // positive only
      @Input() positiveOnly: boolean = false;
    
      // model update
      @Output() ngModelChange: EventEmitter<any> = new EventEmitter();
    
      constructor(
        private renderer: Renderer2,
        private el: ElementRef,
        private currencyPipe: CurrencyPipe,
        private model: NgModel
      ) {
        // set mobile keyboard to numpad
        this.renderer.setAttribute(this.el.nativeElement, 'pattern', 'd*');
        // input needs to be text when formatted
        this.renderer.setAttribute(this.el.nativeElement, 'type', 'text');
    
        // format when model is changed from somewhere else
        this.modelSubscription = this.model.valueChanges.subscribe(value => {
          // dont format while user is editing directly
          if (!this.focused) {
            this.setViewModel(this.currencyPipe.transform(value, this.size));
          }
        });
      }
    
      ngOnDestroy() {
        // unsubscribe from model subscription
        this.modelSubscription.unsubscribe();
      }
    
      @HostListener('focus')
      focus() {
        // user is editing, disable formating
        this.focused = true;
        // needs to be type number when unformatted
        this.renderer.setAttribute(this.el.nativeElement, 'type', 'number');
        // set the view model to raw data value
        this.setViewModel(this.model.value);
    
        // select all in input for easy editing
        $(this.el.nativeElement)
          .one('mouseup', event => {
            event.preventDefault();
          })
          .select();
      }
    
      @HostListener('blur')
      onBlur() {
        // prepare model value
        let newValue = Number(this.model.value);
    
        // get absolute value if only positive values are allowed
        if (this.positiveOnly) {
          newValue = Math.abs(this.model.value);
        }
    
        // emit model change before clearing this.focused
        this.ngModelChange.emit(newValue);
        // input needs to be text when formatted
        this.renderer.setAttribute(this.el.nativeElement, 'type', 'text');
        // format view model
        this.setViewModel(this.currencyPipe.transform(newValue, this.size));
        // clear user focus
        this.focused = false;
      }
    
      private setViewModel(value: any = null): void {
        if (value !== null) {
          this.el.nativeElement.value = value;
        }
      }
    }