繁体   English   中英

Angular 指令:更改 model 不会更新视图

[英]Angular directive: changing the model doesn't update the view

[对不起,我的英语不好]

我有一个简单的贷款计算器。

“Principal”输入具有自动更正值的指令。

如果用户输入 100,则指令会将其乘以 1000。

但是,PMT 不会更新。

示例代码: https://stackblitz.com/edit/angular-srdbew?file=src%2Fapp%2Fthousands.directive.ts

谢谢你的帮助。

您需要 output 指令中的一个事件来更新组件,以便组件识别更改。 现在它正在更改值,但不会在 Angular 上下文中更新。 这里检查实现

更新你的指令

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
 }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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