【问题标题】:Angular directive: changing the model doesn't update the viewAngular 指令:更改模型不会更新视图
【发布时间】:2020-03-03 02:38:56
【问题描述】:

[对不起我的英语不好]

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

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

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

但是,PMT 没有更新。

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

感谢您的帮助。

【问题讨论】:

    标签: angular angular-directive angular-changedetection


    【解决方案1】:

    您需要从指令中输出一个事件来更新组件,以便组件识别更改。现在它正在改变值,但没有在 Angular 上下文中更新。检查实现here

    更新你的指令

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

    【讨论】:

      猜你喜欢
      • 2016-08-13
      • 1970-01-01
      • 2014-07-22
      • 2021-05-21
      • 2016-08-23
      • 2019-02-28
      • 2016-12-04
      • 1970-01-01
      • 2013-05-26
      相关资源
      最近更新 更多