Search code examples
angular6angular7angular-reactive-forms

How to set null for date form field in reactive form in angular 6


How to set null for date filed in reactive form.I tried but not working.Anyone know please help to find the solution.

app.component.html:

<input type="text" class="form-control" formControlName="publishdate" ngbDatepicker #datepicker="ngbDatepicker">

app.component.ts:

this.registerForm = this.fb.group({}); 
this.registerForm.addControl('publishdate', new FormControl('', null));

Solution

  • Change your input be like

    <input type="text" class="form-control" formControlName="publishdate" ngbDatepicker #d="ngbDatepicker">

    And so, the HTML should be like,

    <form class="form-inline" [formGroup]="registerForm">
     <div class="form-group">
       <div class="input-group">
         <input type="text" class="form-control" formControlName="publishdate" ngbDatepicker #d="ngbDatepicker">
         <div class="input-group-append">
           <button class="btn btn-outline-secondary calendar" (click)="d.toggle()" type="button">
           </button>
         </div>
        </div>
       </div>
     </form>
    

    And TS,

    import {Component, OnInit} from '@angular/core';
    import { FormControl, FormGroup, FormBuilder, ValidationErrors } from "@angular/forms";
    
    @Component({
      selector: 'ngbd-datepicker-popup',
      templateUrl: './datepicker-popup.html'
    })
    export class NgbdDatepickerPopup implements OnInit {
    
      registerForm: FormGroup;
    
      constructor(private fb: FormBuilder){}
    
      ngOnInit(){
        this.registerForm = this.fb.group({});
        this.registerForm.addControl('publishdate', new FormControl('', null));
      }
    }
    

    Working Example: https://stackblitz.com/edit/ngb-datepicker-validation-opt-out-vk6maq