i have created a custom input control. I don't want to create any custom validation. I want to use default required, minLength, maxLength etc.I know i can do like this
this.form.controls["firstName"].setValidators([Validators.minLength(1), Validators.maxLength(30)]);
but i can't send form reference from parent component. How can i use setValidator inside textbox component.
// input-box.component.ts
import { Component, Input, forwardRef } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';
@Component({
selector: 'app-input-box',
template:`<label >{{inputdata.label}}</label><br>
<input type="text" required #textBox [value]="textValue" (keyup)="onChange($event.target.value)" />`,
styleUrls: ['./input-box.component.less'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => InputBoxComponent),
multi: true
},
/*{
provide: NG_VALIDATORS,
useExisting: forwardRef(() => InputBoxComponent),
multi: true,
}*/]
})
export class InputBoxComponent implements ControlValueAccessor {
@Input() inputdata: any;
private textValue: any = '';
onChange(value) {
this.textValue = value;
this.propagrateChange(value);
}
private propagrateChange = (_: any) => { };
writeValue(value: any) {
if (this.inputdata.value) {
this.textValue = this.inputdata.value;
this.propagrateChange(this.inputdata.value);
}
}
registerOnChange(fn: (value: any) => any) {
this.propagrateChange = fn;
}
registerOnTouched() { }
}
use in different component
<app-input-box name="textBoxParent_{{index}}" [inputdata]="goaldata" ngModel ></app-input-box>