2

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.

dstj
  • 4,800
  • 2
  • 39
  • 61

1 Answers1

0

Try changing this:

(dateSelect)="update($event)"

to this:

(ngModelChange)="update($event)"

Here is the updated demo.

Update:

Add a required attribute to the inner input field.

Demo 2

Uğur Dinç
  • 2,415
  • 1
  • 18
  • 25
  • That does update the model when clearing the textbox, but the css classes remains ` – dstj May 17 '19 at 19:29
  • @dstj just add a required attribute to the input. Update coming to the demo in a moment. – Uğur Dinç May 17 '19 at 19:45
  • @dstj And if you would like the styling to go down to the child component as well, then change this `.form-control.ng-invalid` with this `::ng-deep .form-control.ng-invalid` – Uğur Dinç May 17 '19 at 19:57
  • thanks. The Demo 2 link is broken it seems. I'll try with `::ng-deep`, but I thought I saw it was deprecated... – dstj May 17 '19 at 21:06
  • @dstj Fixed the link and removed the `::ng-deep`. – Uğur Dinç May 21 '19 at 13:53