gpt4 book ai didi

Angular 7 - ControlValueAccessor - 修剪绑定(bind)到表单的输入值

转载 作者:行者123 更新时间:2023-12-04 16:29:06 28 4
gpt4 key购买 nike

我们在网页上有一个输入字段,必须在用户输入该数据的同时对其进行修剪。由于输入绑定(bind)到 Angular 表单,因此也必须修剪表单中的值。
我使用 Angular 7

import {
Directive,
ElementRef,
forwardRef,
HostListener,
Input,
Renderer2
} from "@angular/core";
import {
ControlValueAccessor,
NG_VALUE_ACCESSOR
} from "@angular/forms";


@Directive({
selector: "[ebppInputTextTrimmer]",
providers: [{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => InputTextTrimmerDirective),
multi: true
}]
})
export class InputTextTrimmerDirective implements ControlValueAccessor {
@Input() prevVal: string;

@Input() isTrimEnabled: boolean;

onChange = (_: any) => {
}

onTouched = () => {
}

constructor(
private _renderer: Renderer2,
private _elementRef: ElementRef) {
}

writeValue(value: any): void {
const normalizedValue = value == null ? "" : value;
this._renderer.setProperty(this._elementRef.nativeElement, "value", normalizedValue);
}

registerOnChange(fn: (_: any) => void): void {
this.onChange = fn;
}

registerOnTouched(fn: () => void): void {
this.onTouched = fn;
}

setDisabledState(isDisabled: boolean): void {
this._renderer.setProperty(this._elementRef.nativeElement, "disabled", isDisabled);
}

@HostListener("input", ["$event.target.value"])
handleInput(inputValue: any): void {
let valueToProcess = inputValue;
if (this.isTrimEnabled) {
valueToProcess = inputValue.trim();
}

this.onChange(valueToProcess);
// set the value that is trimmed in the view
this._renderer.setProperty(this._elementRef.nativeElement, "value", valueToProcess);
}

}

显示的代码对我来说很好用。我想知道是否有更简单的解决方案。

最佳答案

您可以创建一个像下面这样的自定义值访问器作为指令:

const TRIM_VAL_ACCESSOR = new Provider(
NG_VALUE_ACCESSOR, {useExisting: forwardRef(() => TrimValAccessor), multi: true});

@Directive({
selector: 'input[trimval]',
host: { '(keyup)': 'valOnChange($event.target)' },
providers: [ TRIM_VAL_ACCESSOR ]
})
export class TrimValAccessor extends DefaultValueAccessor {
onChange = (_) => {};
onTouched = () => {};

constructor(private renderer:Renderer) {
}

writeValue(value:any):void {
if (value!=null) {
super.writeValue(value.toString().trim());
}
}

valOnChange(el) {
let val = el.value.trim();
this.renderer.setElementProperty(el, 'value', val);
this.onChange(val);
}
}

在模块中给出引用:
declarations: [ TrimValAccessor ]

或在这样的组件中
@Component({
(...)
template: `
<input type="text" trimval/>
`,
directives: [ TrimValAccessor ]
})

在输入标签中使用来修剪值
<input type="text" trimval/>

关于Angular 7 - ControlValueAccessor - 修剪绑定(bind)到表单的输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55626086/

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