I've created component for datepicker that I want to use in many other components in my application. I have some problems becouse it doesn't change value of parent form group control.
Lets get to the code:
export class DatePickerComponent {
@ViewChild('input', {read: ElementRef, static: false}) inputRef: ElementRef;
@Input()
formName?: FormGroup;
@Input()
formControlName: any;
constructor() {
this.formControlName.setValue(['']);
}
onKeyPress = (event) => {
const pressedKey = event.keyCode;
if (
pressedKey !== 8 &&
pressedKey !== 9 &&
pressedKey !== 13 &&
((pressedKey < 48 || pressedKey > 105) || (pressedKey > 57 && pressedKey < 96))
) {
event.preventDefault();
}
}
onKeyUp = (event) => {
const pressedKey = event.keyCode;
const inputString: string = this.formControlName.value;
if (!inputString) {
return;
}
if (inputString.length === 11) {
this.inputRef.nativeElement.value = inputString.slice(0, -1);
return;
}
if (pressedKey === 8 && (inputString.length === 3 || inputString.length === 6)) {
const newValue = inputString.slice(0, -1);
this.formControlName.setValue(newValue);
this.inputRef.nativeElement.value = newValue;
} else if (inputString.length === 2 || inputString.length === 5) {
const newValue = inputString + '/';
this.formControlName.setValue(newValue);
this.inputRef.nativeElement.value = newValue;
}
}
}
And the template:
<div [formGroup]="formName">
<input
class="form-control"
formControlName="{{formControlName}}"
placeholder="DD/MM/YYYY"
name="dp"
ngbDatepicker
#d="ngbDatepicker"
[minDate]="{year: 1930, month: 1, day: 1}"
(click)="d.toggle()"
(keydown)="onKeyPress($event)"
(keyup)="onKeyUp($event)">
</div>
So I wanted to use it in parent component that is form with FormGroup property set to X. To use my component I've added
<app-date-picker [formControlName]="birthDate" [formName]="registerForm"></app-date-picker>
Maybe I did something wrong in parent component:
export class UserFormComponent implements OnInit {
@Input() isRegisterPage: boolean;
@Input() isProfilePage: boolean;
@Input() user: UserInfo;
registerForm: FormGroup;
birthDate: FormControl;
loading: boolean;
.e
.t
.c
How to make my datepicker reusable correctly? Maybe somone can help me?
Fiddle with only datepicker (not used in parent form): https://stackblitz.com/edit/angular-i47zuz-jj5glk?file=app/datepicker-popup.ts