<mat-form-field class="example-full-width">
<input matInput placeholder="Name" [formControl]="uniqueNameControl" (blur)="onInputBlur()">
<mat-error *ngIf="errorState" >Enter a unique name</mat-error>
</mat-form-field>
import { Component,Optional, Self, OnInit } from '@angular/core';
import {NgControl, FormControl} from '@angular/forms';
@Component({
selector: 'app-app-unique-name-text-box',
templateUrl: './app-unique-name-text-box.component.html',
styleUrls: ['./app-unique-name-text-box.component.css']
})
export class AppUniqueNameTextBoxComponent implements OnInit {
uniqueNameControl: FormControl = new FormControl('');
onChanged: any = () => {};
onTouched: any = () => {};
constructor(@Optional() @Self() public ngControl: NgControl) {
if (this.ngControl != null) {
this.ngControl.valueAccessor = this;
}
}
get errorState() {
return this.ngControl.errors !== null && !!this.ngControl.touched;
}
@HostListener('input', ['$event.target.value'])
onInput = (_: any) => {}; ngOnInit() {
const validators = this.ngControl.control.validator;
this.uniqueNameControl.setValidators(validators ? validators : null);
this.uniqueNameControl.updateValueAndValidity();
}
registerOnChange(fn: any): void {
this.onInput = (value: number) => {
fn(value);
};
}
registerOnTouched(fn: any): void {
this.onTouched = fn;
}
writeValue(obj: any = ''): void {
this.uniqueNameControl.patchValue(obj);
}
setInputValue(val = '') {
this.uniqueNameControl.patchValue(val, {emitEvent:false});
this.onChanged(val);
}
onInputBlur(){
this.onTouched()
}
onClick(){
}
}
Không có nhận xét nào:
Đăng nhận xét