我正在尝试让ControlValueAccessor和formControlName与客户的Material Input Textbox一起使用。由于某种原因,代码无法正常工作,并尝试对其进行修复。阅读大量教程,并应用ControlValueAccsor。我们应该使用MAT_INPUT_VALUE_ACCESSOR吗?用材料角最简单的解决方法是什么?
目标是使该样式化文本框与Forms一起使用。
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() Disabled: boolean;
@Input() ReadOnly: boolean;
@Input() NgClass: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:
<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 : ''"
[readonly]="ReadOnly"
[ngClass]="NgClass"
[type]="type ? type: 'text'"
>
</mat-form-field>
</div>
表单组未从InputTextboxComponent
接收值的原因是因为每次onChange
元素从用户接收新值时,都不会调用input
方法。我为input
中的InputTextboxComponent
元素添加了一个变化事件侦听器,并从那里调用了onChange
方法。 (input-text-box.component.ts
的第58行)