角度6:如何将日历/日期选择器与表单交互?

时间:2018-07-06 01:44:47

标签: angular datepicker angular-reactive-forms angular-forms controlvalueaccessor

我有两个div,一个包含日期选择器/日历,允许用户选择他们想要的日期,第二个包含电子邮件,citym和hotel形式,

因此,用户选择一个日期并填写表格,然后单击“书”来提交。

这就是我拥有的

<div class="container about-booking-input">
  <div class="row about-title">
    <div class="col-md-7 about-title_bookingtitle">
      <h2>Booking</h2>
    </div>
  </div>
  <div class="row about-booking">
    <div class="col-sm-4 offset-sm-2 about-booking_calendar">
        <app-calendar></app-calendar>
    </div>
    <div class="col-sm-4 about-booking_form">
      <flash-messages></flash-messages>
      <form [formGroup]="angForm" class="form-element">
        <div class="form-group form-element_email">
          <input type="email" class="form-control info" placeholder="Email" formControlName="email" #email (ngModelChange)="onChange($event)">
        </div>
        <div *ngIf="angForm.controls['email'].invalid && (angForm.controls['email'].dirty || angForm.controls['email'].touched)"
          class="alert alert-danger">
          <div *ngIf="angForm.controls['email'].errors.required">
            Email is required.
          </div>
        </div>
        <div class="input-group mb-3 form-element_city">
          <select class="custom-select" id="inputGroupSelect01" #cityName>
            <option selected *ngFor="let city of cities" [ngValue]="city.name">{{city.name}}</option>

          </select>
        </div>
        <div class="input-group mb-3 form-element_hotel">
          <select class="custom-select" id="inputGroupSelect01" #hotelName>
            <option selected *ngFor="let hotel of hotels" [ngValue]="hotel.name">{{hotel.name}}</option>

          </select>
        </div>
        <div class="form-group">
          <button type="submit" (click)="addReview(email.value, cityName.value , hotelName.value)" class="btn btn-primary btn-block form-element_btn"
            [disabled]="!validEmail">Book</button>
        </div>
      </form>

    </div>
  </div>
</div>

Visul的长相看起来很喜欢。 enter image description here

现在,在谷歌搜索和谷歌搜索都无济于事之后,我可以提交没有日期的表格

注意:我正在使用此datepicker ui:ignite -ui angular https://www.infragistics.com/products/ignite-ui-angular/angular/components/calendar.html

  

问题

如何将日历与表单整合在一起并能够提交?

1 个答案:

答案 0 :(得分:2)

您必须使您的app-calender组件成为自定义表单控件。一篇不错的文章:https://blog.thoughtram.io/angular/2016/07/27/custom-form-controls-in-angular-2.html

在坚果壳中,您的AppCalenderComponent必须实现ControlValueAccessor接口才能与formGroup通信。为ControlValueAccessor成功实现AppCalenderComponent后,可以将其包含在以下格式中:

<form [formGroup]="form">
  <app-calendar formControlName="nameOfTheDatePickerControl"></app-calendar>
</form>