gpt4 book ai didi

javascript - 指令不解析初始值

转载 作者:行者123 更新时间:2023-11-30 06:24:02 24 4
gpt4 key购买 nike

目前,我正在研究一个指令,该指令必须在用户不关注输入字段时将数字显示为货币。在我从我的服务器重新加载数据并为输入字段提供起始值之前,这一直很好用。

每当我初始化输入字段的值时,解析都不会应用,直到用户聚焦并退出输入字段(这是正常行为)。即使用户尚未输入(焦点)和退出(模糊)该字段,我也在尝试应用数字格式。

Representation of the problem

左边的字段是我加载页面时的输入,右边的字段是我关注它并退出该字段后的输入。即使用户尚未与输入交互,我也需要显示正确的表示。

我已经尝试在构造函数和 ngInit 上应用管道,但这些点的值仍然是“0”,所以我认为我不能那样做。我还尝试绑定(bind) ngOnChanges 生命周期和“更改”hostListener 事件,但都不起作用。

有什么方法可以让它发挥作用,或者它会成为我页面上的一项功能吗?

我的指令:

@Directive({
selector: '[appCurrencyFormatter]'
})
export class CurrencyFormatterDirective implements OnInit, OnChanges {

private el: HTMLInputElement;

constructor(
private elementRef: ElementRef,
private currencyPipe: CurrencyPipe) {
this.el = this.elementRef.nativeElement;
}

ngOnInit() {
// This doesn't work. value at this point is an empty string.
this.el.value = this.currencyPipe.transform(this.el.value);
}

@HostListener('change', ['$event.target.value'])
ngOnChanges(changes) {
console.log('change'); // only triggers when user changes the value.
// Not when value is set during initialization.
}

@HostListener('focus', ['$event.target.value'])
onFocus(value) {
this.el.value = this.currencyPipe.parse(value);
}

@HostListener('blur', ['$event.target.value'])
onBlur(value) {
this.el.value = this.currencyPipe.transform(value);
}

}

我的 html 输入:

<input type="text"
[(ngModel)]="testNumber"
appCurrencyFormatter />

testNumber 刚刚在 ngOnInit(){...}

中初始化为值 22221

我目前使用的是最新版本的 angular6。

最佳答案

那是因为指令需要时间来抓取模型。你可以尝试做这样的事情:

import { Directive, OnInit, ElementRef } from '@angular/core';

@Directive({
selector: '[appMyDir]'
})
export class MyDirDirective implements OnInit {

constructor(private el: ElementRef) { }

ngOnInit() {
setTimeout(() => {
console.log(this.el.nativeElement.value)
}, 0);
}

}

关于javascript - 指令不解析初始值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51526612/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com