title: Setting the default value of an ng-bootstrap field (ngModels can't use getter/setter)
body: <p>I'm using an <a href="https://ng-bootstrap.github.io/#/components/datepicker" rel="nofollow noreferrer">ng-boostrap datepicker</a> field in one of my forms and I'd like to initialize it with a default value.</p>
  
  <p>In a "standard" form, I can use either <code>formControlName</code> or <code>ngModel</code> and it works fine:</p>
  
  <pre class="lang-html prettyprint-override"><code>&lt;!-- formControlName --&gt;
  &lt;input ngbDatepicker #d="ngbDatepicker" formControlName="dateFieldName"&gt;
  &lt;!-- ngModel --&gt;
  &lt;input ngbDatepicker #d="ngbDatepicker" [(ngModel)]="myDateProp"&gt;
  </code></pre>
  
  <p>My problem is I have wrapped the datepicker in my own custom field, i.e. a custom component implementing <code>ControlValueAccessor</code>.</p>
  
  <p>In this scenario, <strong>the datepicker is no longer aware of its parent form and the corresponding model</strong>. So how can I initialize the datepicker field?</p>
  
  <ul>
  <li><code>formControlName</code> is not an option (my custom field component doesn't and shouldn't have access to the model of its parent form).</li>
  <li><code>ngModel</code> seemed easier since it's just a binding to a local property but my entire form freezes as soon as I add the <code>[(ngModel)]</code> directive to the datepicker field.</li>
  </ul>
  
  <p>Here's the code for my custom field component so far:</p>
  
  <pre class="lang-ts prettyprint-override"><code>@Component({
    selector: 'field-datetime',
    template: `
      &lt;div class="input-group"&gt;
        &lt;input class="form-control" ngbDatepicker #d="ngbDatepicker"&gt;
        &lt;div class="input-group-addon" (click)="d.toggle()" &gt;
          &lt;i class="fa fa-calendar" style="cursor: pointer;"&gt;&lt;/i&gt;
        &lt;/div&gt;
      &lt;/div&gt;`,
    providers: [
      { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() =&gt; FieldDateTimeComponent), multi: true }
    ]
  })
  export class FieldDateTimeComponent implements ControlValueAccessor {
    private _dateTimeObj: DateTime;  // Date is stored as an object internally
  
    propagateChange = (_: any) =&gt; {};
  
    // Write a new value to the element (from the form model into the view).
    writeValue(timestamp: number) {
      // Parse the timestamp to store it as an object internally.
      this._dateTimeObj = moment(timestamp).toObject();
      this.propagateChange(this._dateTimeObj);
    }
  
    registerOnChange(fn: any) {
      this.propagateChange = fn;
    }
  
    registerOnTouched(fn: any) {}
  
    // This is the property I'd like to bind to the field, i.e.:
    // &lt;input ngbDatepicker [(ngModel)]="dateObj"&gt;
    // THIS IS WRONG. DO NOT USE A GETTER FOR A NGMODEL. SEE ANSWER BELOW.
    get dateObj() {
      return {day: this._dateTimeObj.date, month: this._dateTimeObj.months, year: this._dateTimeObj.years};
    }
  
  }
  </code></pre>