Ray Bond
Ray Bond

Reputation: 487

Custom datepicker options in Angular JHipster project

I am new to JHipster and learning how it structured and customized.

Not globally, but in one component view only I want to know where to modify the generated date-picker, in this case to only allow selecting a date that falls on a Monday.

The generated component html:

<div class="form-group">
    <label class="form-control-label" jhiTranslate="deploymentApp.plan.startDate" for="field_startDate">Start Date</label>
    <div class="d-flex">
         <input id="field_startDate" type="datetime-local" class="form-control" name="startDate" formControlName="startDate" placeholder="YYYY-MM-DD HH:mm"/>
    </div>
</div>

And from the component.ts. The only date related code block:

ngOnInit(): void {
this.activatedRoute.data.subscribe(({ plan }) => {
  if (!plan.id) {
    const today = moment().startOf('day');
    plan.startDate = today;
  }

  this.updateForm(plan);

  this.areaService.query().subscribe((res: HttpResponse<IArea[]>) => (this.areas = res.body || []));
  });
}

In the Javascript/HTML this would have be achieved with java script inside the script tags.

Where is the datepicker customised in JHipster?

Upvotes: 3

Views: 508

Answers (2)

vicpermir
vicpermir

Reputation: 3702

You don't need to add new dependencies since JHipster already integrates ng-bootstrap.

To enable ng-bootstrap datepicker you only have to change this:

<input id="field_startDate" type="datetime-local" class="form-control" name="startDate" 
       formControlName="startDate" placeholder="YYYY-MM-DD HH:mm"/>

into this:

<input id="field_startDate" class="form-control" name="startDate" 
       formControlName="startDate" placeholder="YYYY-MM-DD"
       ngbDatepicker #d="ngbDatepicker" (click)="d.toggle()" [markDisabled]="markDisabled"/>

If you notice I've added a "markDisabled" property that points to a function of the same name, so in your component TS file you'll need to add something like this:

markDisabled(date: NgbDate): boolean {
  const dateMoment = moment(date.year + '-' + date.month + '-' + date.day, 'YYYY-MM-DD');
  return dateMoment.isoWeekday() !== 7;
}

Since moment.isoWeekday() returns a number [1-7] for the day of the week this should disable all days except for mondays.

There are many other ways to do this, e.g. you could use NgbCalendar.getWeekday() instead of moment. I just tend to use moment for everything date related for consistency.

Upvotes: 3

Falydoor
Falydoor

Reputation: 462

Not sure what you wanna achieve is possible since JHipster uses browser's datepicker: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/datetime-local

The type attribute might help you achieve what you want.

Upvotes: 1

Related Questions