Angular 使用指令在模糊和加载时对窗体设置角度数格式,也不应格式化formControl数据
我正在尝试对表单输入字段进行数字格式化,在加载和模糊时应在其中对数字进行格式化。在聚焦到字段时,我会将其转换为普通文本。formgroup中的值也不应格式化 App.htmlAngular 使用指令在模糊和加载时对窗体设置角度数格式,也不应格式化formControl数据,angular,angular6,angular-directive,angular-pipe,Angular,Angular6,Angular Directive,Angular Pipe,我正在尝试对表单输入字段进行数字格式化,在加载和模糊时应在其中对数字进行格式化。在聚焦到字段时,我会将其转换为普通文本。formgroup中的值也不应格式化 App.html <div> <form [formGroup]='rForm' (ngSubmit)= "addPost(rForm.value)"> <div class="form-container" > <div class="row columns" > &
<div>
<form [formGroup]='rForm' (ngSubmit)= "addPost(rForm.value)">
<div class="form-container" >
<div class="row columns" >
<h1>My Reactive form</h1>
<label>Name
<input type="text" formControlName="name" appDecimalFormat >
</label>
<label>Description
<textarea formControlName="description"></textarea>
</label>
<label for="validate">Minimum of 3 characters</label>
<input type="checkbox" name="validate" formControlName="validate" value="1">On
<input type="submit" class="button expnded" value="Submit Form" [disabled]="!rForm.valid">
</div>
</div>
</form>
</div>
<ng-template #forminfo>
<div class="form-container">
<div class="row columns">
<h1>{{name}}</h1>
<p>{{ description }}</p>
<input type="button" (click)=""
</div>
</div>
</ng-template>
number-format-directive.ts
我用这个指令来设置数字的格式,请帮我整理一下
import { Directive, HostListener, HostBinding, Renderer2, ElementRef } from '@angular/core';
import {DecimalPipe} from '@angular/common';
@Directive({
selector: '[appDecimalFormat]'
})
export class DecimalFormatDirective {
constructor(private decimalPipe: DecimalPipe, private renderer: Renderer2, private el: ElementRef) {
}
@HostListener('focus') onFocus($event){
console.log(event.target.value)
this.backgroundColor = 'silver';
this.renderer.setAttribute(this.el.nativeElement,'input', this.decimalPipe.transform(event.target.value));
}
@HostListener('blur') onBlur($event){
console.log(event.target.value)
this.backgroundColor = 'white';
console.log(this.decimalPipe.transform(event.target.value));
this.renderer.setAttribute(this.el.nativeElement,'input', this.decimalPipe.transform(event.target.value));
}
@HostBinding('style.background-color') get setColor(){
return this.backgroundColor;
}
private backgroundColor = 'white';
}
注射管道不是一件好事。相反,您可以使用从@angular/common包导出的函数。例如,可以使用use formatNumber 您可以按如下方式将该值设置回输入框
this.el.value = formatNumber(num);
formatNumber()是从@angular/common package导出的fn。有什么问题,当前的行为是什么,您期望什么?我无法在表单输入字段中呈现格式化数据。。我不确定formGroup中的数据会是怎样的。。输入字段的渲染器使用是否正确?iam使用this.renderer.setAttribute(this.el.nativeElement,'input',this.decimalPipe.transform(event.target.value)this.el.value没有将值设置回输入字段从输入和测试中删除formControlName指令。this.el.nativeElement.value,这对我有效,无需删除formControlName。请将其设置为解决方案,以便帮助其他人
this.el.value = formatNumber(num);