我有一个角度 16 项目 我有一个数字输入,使用
formControls
进行验证
因为我们经常使用此输入,所以我将其放入自定义组件中以使我的工作更轻松。
我使用primeng inputNumbers
我的custom-input-number代码摘要如下
html 文件:
<span class="p-float-label w-100" [formGroup]="form">
<p-inputNumber
formControlName="number"
[disabled]="disabled"
(onInput)="onChange($event)"
(onBlur)="onTouched()">
</p-inputNumber>
<label for="{{ id }}" class="custom-input-label">{{ label }}</label>
</span>
<small class="unselectable">
{{textValidators}}
</small>
打字稿文件:
import { ChangeDetectorRef, Component, EventEmitter, forwardRef, Input, OnInit, Output } from '@angular/core';
import { AbstractControl, ControlValueAccessor, FormControl, FormGroup, NG_VALIDATORS, NG_VALUE_ACCESSOR, ValidationErrors } from '@angular/forms';
@Component({
selector: 'ngx-custom-input-number',
templateUrl: './custom-input-number.component.html',
styleUrls: ['./custom-input-number.component.scss'],
providers: [
{
provide: NG_VALIDATORS,
useExisting: forwardRef(() => CustomInputNumberComponent),
multi: true,
},
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CustomInputNumberComponent),
multi: true,
},
],
})
export class CustomInputNumberComponent implements OnInit, ControlValueAccessor {
form: FormGroup;
ngModel;
selectedData = null;
selectedCountry;
getValidators;
textValidators: string = '';
@Input() mode;
@Input() label;
onChange!: (value: string) => void;
@Output() onBlur = new EventEmitter();
constructor(private cdr: ChangeDetectorRef) {
this.ngModel = this.setNgModel;
}
ngOnInit(): void {
this.form = new FormGroup({
number: new FormControl(this.setDefaultValue),
});
}
onTouched() {
this.onBlur.emit(this.form.get('number').value)
}
writeValue(val: any): void {
if (val) {
this.form.get('number').setValue(val, { emitEvent: false });
} else {
this.form.get('number').setValue(null);
}
}
registerOnChange(fn: any): void {
this.onChange = fn;
this.form.get("number").valueChanges.subscribe(fn);
}
registerOnTouched(fn: any): void {
this.onTouched = fn;
}
setDisabledState?(isDisabled: boolean): void {
isDisabled
? this.form.disable()
: this.form.enable();
}
validate(c: AbstractControl): ValidationErrors | null {...}
}
当我想在另一个组件中使用它时,这是完全正常 我用它并给它
formControlName
像这样
<form [formGroup]="form"
<ngx-custom-input-number [label]="..." formControlName="number"> </ngx-custom-input-number>
</form>
现在我的问题是当输入值到达服务器时 一切都会被毁掉进入服务器的金额
number : {
formattedValue : '423',
originalEvent : { isTrusted : true},
value : 4234
}
我只想要这个
value
而不想要其他东西
我的问题是我无法改变整个项目
我想尽可能地更改自定义组件,这样整个项目就不需要更改
注意:我将项目从 Angular12 升级到 Angular16,这 Angular12 中不存在问题
编辑 HTML 代码如下。
<span class="p-float-label w-100" [formGroup]="form">
<p-inputNumber
formControlName="number"
[disabled]="disabled"
(onInput)="onChange($event.value)"
(onBlur)="onTouched()">`enter code here`
</p-inputNumber>
<label for="{{ id }}" class="custom-input-label">{{ label }}</label>
</span>