I am trying to apply Error Validation style with ControlValueAccessor in custom Material Input Textbox.
(我正在尝试在自定义材料输入文本框中使用ControlValueAccessor应用错误验证样式。)
Ever since applying this custom component, all the red border validation status with formControlName/FormBuilders do not show, for required, minlength, etc. It worked natively (out of the box) with Angular Material textbox, until the custom control was applied. (自从应用此自定义组件以来,所有带有formControlName / FormBuilders的红色边框验证状态都不会显示(对于必填项,最小长度等)。它与Angular Material文本框一起(开箱即用)工作,直到应用了自定义控件。)
Goal is to have custom textbox working with Form validation.
(目标是使自定义文本框与表单验证一起使用。)
This showed naturally with matInput textbox. (使用matInput文本框自然显示了这一点。)
Update: Posted answer;
(更新:发布答案;)
however not sure if its most efficient one, trying to get Saloo answer working also (if someone can post stackbliz, would be great), open to any more efficient options (但是不确定是否最有效的方法(试图使Saloo答案也起作用)(如果有人可以发布stackbliz,那将是不错的选择),是否接受任何更有效的方法)
Typescript:
(打字稿:)
import { Component, OnInit, Input, ViewChild, EventEmitter, Output, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
@Component({
selector: 'app-input-textbox',
templateUrl: './input-textbox.component.html',
styleUrls: ['./input-textbox.component.scss'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => InputTextboxComponent),
multi: true
}
]
})
export class InputTextboxComponent implements OnInit, ControlValueAccessor {
@Input() MaxLength: string;
@Input() Value: string;
@Input() type: string;
@Input() Label: string;
@Input() PlaceHolder: string;
@Output() saveValue = new EventEmitter();
@Output() onStateChange = new EventEmitter();
disabled: boolean;
constructor() { }
ngOnInit() {
}
saveValueAction(e) {
this.saveValue.emit(e.target.value);
}
onChange(e) {
this.Value = e;
}
onTouched() {
this.onStateChange.emit();
}
writeValue(value: any) {
this.Value = value ? value : '';
}
registerOnChange(fn: any) { this.onChange = fn; }
registerOnTouched(fn: any) { this.onTouched = fn; }
setDisabledState(isDisabled) { this.disabled = isDisabled; }
}
HTML:
(HTML:)
<div class="input-wrap">
<mat-form-field appearance="outline">
<mat-label>{{Label}}</mat-label>
<input matInput
[attr.maxlength] = "MaxLength"
[value]="Value ? Value : ''"
[placeholder]="PlaceHolder ? PlaceHolder : ''"
[type]="type ? type: 'text'"
(input)="onChange($event.target.value)"
>
</mat-form-field>
</div>
Trying to incorporate this answer with the natural error styling from Angular Material textbox, Inheriting validation using ControlValueAccessor in Angular
(尝试将此答案与Angular Material文本框中的自然错误样式合并, 使用Angular中的ControlValueAccessor继承验证)
ask by Artportraitdesign1 translate from so 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…