一旦用户在UI中输入值,我就无法重置验证。
在调试器中,我可以看到值传递到onModelChange
,它永远不会重置。我希望验证知道控件中有一个值而不是阻塞它并将值设置为IsInvalid为false。
我需要在[formControl]的html中添加什么来验证值?
输入值后,应删除UI红色框
HTML:
<div contenteditable="true"
style="width: 100% !important; overflow: hidden"
class="form-control sentence-part-values-inline sentence-part-values-inline-textbox-number"
[attr.id]="editorId">
</div>
打字稿:
@Output() public modelchange: EventEmitter<any> = new EventEmitter();
public onModelChange(): void {
this.validate();
this.modelchange.next(this.getModel());
}
initControlGroup(fb: FormBuilder) : FormGroup {
return fb.group({
"value": ['', Validators.required]
});
}
(<any>window).CKEDITOR.instances[this.editorId].on("change", () => {
self.model.Value = (<any>window).CKEDITOR.instances[self.editorId].getData();
self.onModelChange();
});
将formControl设置为value更新html
<div contenteditable="true"
style="width: 100% !important; overflow: hidden"
class="form-control sentence-part-values-inline sentence-part-values-inline-textbox-number"
[formControl]="value"
[attr.id]="editorId">
</div>
ts班
interface SentencePartModel extends SentencePartModelBase {
Type: SentencePartType;
Value: string;
}
很高兴看到完整的代码,但我相信你需要创建一个实现ControlValueAccessor
的组件(正如许多注释所示),你正在尝试使用div
元素作为一个不起作用的表单控件,您需要的是创建一个自定义表单控件并在此组件中实现您的编辑器(请参阅https://alligator.io/angular/custom-form-control/)。
您的组件应如下所示:
@Component({
selector: 'my-component',
...,
providers: [
{ provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => MyComponent), multi: true }
]
})
export class MyComponent implements OnInit, ControlValueAccessor {
@Input() disabled = false;
theModel: string;
onChange: (value: string) => {};
onTouched: () => {};
...
writeValue(value: string): void {
// allows angular to bind to the model (theModel)
this.theModel = value;
this.onChange(this.value);
}
registerOnChange(fn: (value: string) => void): void {
this.onChange = fn;
}
registerOnTouched(fn: () => void): void {
this.onTouched = fn;
}
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
}
}
您的HTML模板将构成此组件的模板,您可以像现在一样将绑定添加到change
事件中,在更改事件中,您可以调用this.onChange(value)
来触发模型更新
您的用法是在父组件中创建form
并在formControlName
上设置my-component
父组件模板:
<!-- where myEditor is the name of the form control in your FormGroup -->
<my-component formControlName="myEditor"></my-component>
希望这可以帮助