我已经通过模板驱动的表单实现了一个自定义表单控件,该表单将输入包装在 html 中并添加标签等。它与 ngModel 上的 2way 数据绑定很好地与表单对话。问题是,表单在初始化时会自动标记为脏。有没有办法防止这种情况发生,这样我就可以在表单上使用这些属性并且它们是准确的?
自定义选择器(除了自动被标记为脏之外,这很好用):
<form class="custom-wrapper" #searchForm="ngForm">
{{searchForm.dirty}}
{{test}}
<custom-input name="testing" id="test" label="Hello" [(ngModel)]="test"></custom-input>
<pre>{{ searchForm.value | json }}</pre>
</form>
自定义输入模板:
<div class="custom-wrapper col-xs-12">
<div class="row input-row">
<div class="col-xs-3 col-md-4 no-padding" *ngIf="!NoLabel">
<label [innerText]="label" class="inputLabel"></label>
</div>
<div class="col-xs-9 col-md-8 no-padding">
<input pInput name="cust-input" [(ngModel)]="value" />
</div>
</div>
</div>
自定义输入组件:
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from "@angular/forms";
import { Component, Input, forwardRef } from "@angular/core";
@Component({
selector: "custom-input",
template: require("./custom-input.component.html"),
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => QdxInputComponent),
multi: true
}
]
})
export class CustomInputComponent implements ControlValueAccessor {
@Input("value") _value = "";
get value() {
return this._value;
}
set value(val: string) {
this._value = val;
this.propagateChange(val);
}
@Input() noLabel: boolean = false;
@Input() label: string = "Label required";
propagateChange = (_: any) => {};
writeValue(value) {
if (value !== undefined) {
this.value = value;
}
}
registerOnChange(fn) {
this.propagateChange = fn;
}
registerOnTouched(fn) {}
}