简体   繁体   中英

Angular directive: changing the model doesn't update the view

[Sorry for my bad English]

I have a simple loan calculator.

The "Principal" input has a directive that auto-corrects the value.

If the user types 100, then the directive will multiply it with 1000.

But, the PMT doesn't update.

Sample code: https://stackblitz.com/edit/angular-srdbew?file=src%2Fapp%2Fthousands.directive.ts

Thanks for any help.

You need to output an event from your directive to update the component, so that component recognize the changes. Right now it's changing the value but not updating in Angular context. check the implementation here

update your directive

import { Directive, HostListener, ElementRef, OnInit, EventEmitter, Output } from "@angular/core";
@Directive({
 selector: '[appThousands]'
})
export class ThousandsDirective {
 // Here declare output event
 @Output() ngModelChange = new EventEmitter(); //declare output
 constructor(private element: ElementRef<HTMLInputElement>) { }

 @HostListener("change")
 onChange() {
  const input = this.element.nativeElement;
  const value = input.value;

  if (value.startsWith("=")) {
    let exactValue = value.substr(1);
    input.value = exactValue;
  }

  else if (+value < 1000) {
    input.value = (+value * 1000).toString();
  }
  // emit event here
  this.ngModelChange.emit(this.element.nativeElement.value); //add event here
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM