I have an Angular 7 custom component to wrap an ng-bootstrap NgbDatePickerInput
.
form = this.fb.group({
date2: [null, Validators.required]
});
<date-editor formControlName="date2"></date-editor>
How can I propagate that formControl
's Validator.required
to that inner component? So that a blank text is invalid and the <input>
has the nb-invalid
style applied, exactly like if the datepicker wasn't in a custom control.
Stackblitz reproduction of my problem.
My custom component is:
import { Component } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
@Component({
selector: 'date-editor',
template: `
<input class="form-control" placeholder="mm/dd/yyyy" [(ngModel)]="value" ngbDatepicker #dp="ngbDatepicker" container="body" (focus)="dp.open()" (dateSelect)="update($event)">
`,
providers: [{
provide: NG_VALUE_ACCESSOR,
useExisting: DateEditorComponent,
multi: true
}]
})
export class DateEditorComponent implements ControlValueAccessor {
value;
propagateChange = (_: any) => { };
writeValue(obj: any): void {
this.value = obj;
}
registerOnChange(fn: any): void {
this.propagateChange = fn;
}
registerOnTouched(fn: any): void { }
update($event) {
this.propagateChange($event);
}
}
I've seen this other SO post and tried working with it, but without success. Clearing the input
text would not trigger the ng-invalid
state.