这是我第一次为嵌入式文本框/标签编辑创建Angular自定义控件。我的整个代码运行良好,但是我已经通过自定义逻辑处理了验证。 (通过检查值不为null或在onChange事件上匹配RegEx)。
我认为我可以使用NG_VALUE_VALIDATORS
或类似的Angular技术更轻松地合并相同的功能。但是,我不知道如何使用它。如果有人可以帮助您,那就太好了!
import { Component, OnInit, forwardRef, Input, EventEmitter, Output, HostListener } from '@angular/core';
import { NG_VALUE_ACCESSOR } from '@angular/forms';
const VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => InlineEditMultilineTextboxComponent),
multi: true
};
@Component({
selector: 'app-inline-edit-multiline-textbox',
templateUrl: './inline-edit-multiline-textbox.component.html',
providers: [VALUE_ACCESSOR]
})
export class InlineEditMultilineTextboxComponent implements OnInit {
@Input() label: string = "Enter value here";
@Input() name: string;
@Input() required: boolean = true;
@Input() data: Array<string> = [];
@Output() valueChange = new EventEmitter();
private _value: string = '';
private preValue: Array<string> = [];
public editing: boolean = false;
private isBlank: boolean = false;
public onChange: any = Function.prototype;
public onTouched: any = Function.prototype;
pre: any;
constructor() { }
ngOnInit(): void {
}
get value(): any {
return this._value;
}
set value(v: any) {
this.checkRequired();
if (v !== this._value) {
this._value = v;
this.onChange(v);
}
}
writeValue(value: any) {
this.checkRequired();
this._value = value;
}
public registerOnChange(fn: (_: any) => {}): void {
this.onChange = fn;
}
public registerOnTouched(fn: () => {}): void {
this.onTouched = fn;
}
@HostListener('document:click', ['$event'])
clickout($event) {
if ($event.target.classList.contains("form-control")) {
return;
}
if ($event.target.classList.contains("fa-save") || $event.target.classList.contains("btnsave")) {
this.preValue = this.data.map(x => x);
}
else {
this.data = this.preValue.map(x => x);
this.editing = false;
}
}
beginEdit() {
this.checkRequired();
this.preValue = this.data.map(x => x);
this.editing = true;
}
checkRequired() {
var arr = this.data.join("");
if (arr.length < 1) {
this.isBlank = true;
}
else {
this.isBlank = false;
}
}
keyupTextbox(value, index) {
this.data[index] = value;
this.checkRequired();
}
save(): void {
this.valueChange.emit(this.data);
}
}