我正在使用 Angular 10 并从“@angular/common”导入CurrencyPipe,并根据找到的建议,我在模板中实现了以下内容 -
<p>{{Amount | currency}}</p>
这显示了以 $ 为单位的金额值,并像预期的那样带有逗号,但不显示文本框字段中的值,而是显示在文本框的顶部。请看下面的截图 -
如何将此值分配给 [Value] 属性,以便它显示在文本框中?
这是一个大讨论的问题。我觉得更好的选择是使用指令
import { NgControl } from '@angular/forms';
@Directive({
selector: '[onblur]',
})
export class BlurFormatDirective implements OnInit {
@Input('onblur') transform: (string) => string | null;
@HostListener('blur') onBlur() {
if (this.transform && this.control)
this.el.nativeElement.value = this.transform(this.control.value);
}
@HostListener('focus') onFocus() {
if (this.transform && this.control)
this.el.nativeElement.value = this.control.value?
this.control.value:'';
}
constructor(
private el: ElementRef,
@Optional() @Host() private control: NgControl
) {}
ngOnInit() {
setTimeout(() => {
this.onBlur()
});
}
}
现在我们可以使用一些像
<input [onblur]="transform" [(ngModel)]="name">
where
name = 'Angular ' + VERSION.major;
transform(value:string)
{
//e.g. transform a string
return value.split('').map((x,i)=>i%2?x:'*').join('');
//or
return formatCurrency(+value,'en-GB',"$")
}
see 堆栈闪电战
注意:该指令仅适用于模板驱动表单或反应表单
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)