NgbTimepicker – When meridian is true: error Cannot read property ‘hour’ of undefined

Under timepicker.ts you’ll see that model isn’t initialized, only declared. Model is essentially undefined until angular2 initiates the binding with ControlValueAccessor and writeValue() is called.

export class NgbTimepicker implements ControlValueAccessor,
    OnChanges {
  disabled: boolean;
  model: NgbTime;

I’m not sure why it’s working in your demo, however I can only assume that something has changed between versions and this fix will be needed as I’m on the latest (2.2.0) Also doesn’t work with (2.0.2).

If you’ll notice below that we don’t hold model accountable when trying to access parameters from it until we get to checking if meridian is true.

            <input type="text" class="form-control" maxlength="2" size="2" placeholder="MM"
              [value]="formatMinSec(model?.minute)" (change)="updateMinute($" 
              [readonly]="readonlyInputs" [disabled]="disabled">
          <template [ngIf]="seconds">
            <input type="text" class="form-control" maxlength="2" size="2" placeholder="SS"
              [value]="formatMinSec(model?.second)" (change)="updateSecond($" 
              [readonly]="readonlyInputs" [disabled]="disabled">
          <template [ngIf]="meridian">
              <button type="button" class="btn btn-outline-primary" (click)="toggleMeridian()">{{model.hour >= 12 ? 'PM' : 'AM'}}</button>

I believe we need to soak up the undefined reference by treating the model as possibly undefined if the meridian is set to true. Currently we’re expecting there to be an hour key on a possibly defined object and that doesn’t work since model isn’t set on class initiation, only when a change to the model is made and detected through controlvalueaccessor.

1 possible answer(s) on “NgbTimepicker – When meridian is true: error Cannot read property ‘hour’ of undefined

  1. I started facing the same error under the following conditions

    1. Component is under a form tag hence provided name attribute for the ngb-timepicker
    2. Meridian is true

    Worked for me when meridian is true and NOT under form tag and no name attribute was provided in the ngb-timepicker component. Not sure if this helps.

    My workaround now is using [ngModelOptions]=”{standalone: true}” so this is not processed by form.