我有一個關於保存數值的html輸入框的指令。當用戶將一個數字粘貼到文本框中時,我有一個「清除」數字的指令(去掉逗號,美元符號等)。清潔代碼似乎工作正常,但是我的模型沒有使用已清理的值進行更新,即使文本框顯示了已清理的值。Angular2 - 指令沒有更新模型
如何使用新值更新我的模型?
這裏是一個精簡例如:
app.ts
@Component(
@Component({
selector : 'my-app',
template : `
<div>
<br/>
<br/>
<p>Stack Overflow person - give focus to text box and then lose focus by clicking elsewhere in the screen. <br/>The model is not updated.</p>
<br/>Model value: {{ balanceAmount }}
<br/>
<br/>
<input type="text" [(ngModel)]="balanceAmount" myCurrencyFormatter /><br/>
</div>
`,
})
export class App {
name:string;
constructor(private mycurpipe: MyCurrencyPipe) {
this.balanceAmount = 1234567.89;
}
}
貨幣-格式化-Directive.ts
@Directive({ selector: "[myCurrencyFormatter]" })
export class MyCurrencyFormatterDirective implements OnInit {
private el: any;
constructor(
private elementRef: ElementRef,
private currencyPipe: MyCurrencyPipe
) {
this.el = this.elementRef.nativeElement;
}
ngOnInit() {
this.el.value = this.currencyPipe.transform(this.el.value);
}
@HostListener("focus", ["$event.target.value"])
onFocus(value) {
this.el.value = this.currencyPipe.parse(value); // opossite of transform
}
@HostListener("blur", ["$event.target.value"])
onBlur(value) {
this.el.value = this.cleanNumber(value); //"987654" ;//this.currencyPipe.transform(value);
}
cleanNumber (value: number) {
return 8888888; // clean logic goes here, removed for plunk example
}
}
你能更新組件中的模型嗎? –
是的 - 例如,在我的現實生活應用程序中,用於獲取模型的值並執行一些計算並更新模型「TotalValue」。 – ClaytonK