Skip to content

reactive forms (bootstrap 4 and font awesome)

kekeh edited this page Jun 15, 2019 · 1 revision
<!-- add the following snippet inside your template -->
<form [formGroup]="myForm" (ngSubmit)="onSubmit()" novalidate>
    <div class="input-group">
        <input class="form-control" placeholder="Select a date" angular-mydatepicker name="myDate" 
          formControlName="myDate"[options]="myOptions" #dp="angular-mydatepicker"/>

        <div class="input-group-append">
          <button type="button" class="btn btn-secondary" (click)="dp.clearDate()">
            <i class="fa fa-close"></i>
          </button>
        </div>

        <div class="input-group-append">
          <button type="button" class="btn btn-secondary" (click)="dp.toggleCalendar()">
            <i class="fa fa-calendar-o"></i>
          </button>
        </div>
    </div>

    <div class="btnGroup">
        <button class="button" type="submit" [disabled]="myForm.controls.myDate.errors">Submit</button>
        <p class="error" *ngIf="myForm.controls.myDate.errors">Date is required!</p>
    </div>
</form>
import {IAngularMyDpOptions, IMyDateModel} from 'angular-mydatepicker';
// other imports are here...

export class MyTestApp implements OnInit {

  myOptions: IAngularMyDpOptions = {
    dateRange: false,
    dateFormat: 'dd.mm.yyyy'
    // other options...
  };

  private myForm: FormGroup;

  constructor(private formBuilder: FormBuilder) { }

  ngOnInit() {
    // Initialize to today date
    let model: IMyDateModel = {isRange: false, singleDate: {jsDate: new Date()}, dateRange: null};
    this.myForm = this.formBuilder.group({
      myDate: [model, Validators.required]
      // other controls are here...
    });
  }

  setDate(): void {
    // Set today date using the patchValue function
    let model: IMyDateModel = {isRange: false, singleDate: {jsDate: new Date()}, dateRange: null};
    this.myForm.patchValue({myDate: model);
  }

  clearDate(): void {
    // Clear the date using the patchValue function
    this.myForm.patchValue({myDate: null});
  }
}