[英]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.