Search code examples
angulartypescriptdateangular-materialangular-moment

Angular datepicker, can't set default date without ngModel


I'm using FormBuilder to generate my forms, but I can't set a default date value to the date inputs (in some cases I need a pre-established date for these forms, i.e edit forms)

Using FormGroup's setValue function won't work, I was able to get it working by binding a ngModel to the datepicker input, but doesn't feel like the correct way of doing.

Stackblitz demo: https://stackblitz.com/edit/angular-h45fid

Is this possible or am I doing something wrong?


Solution

  • Try this:

    this.formGroup = this.fb.group({
      datef: [this.today.toISOString(), [Validators.required]],
      dateng: [{ value: moment(this.today).valueOf() }, [Validators.required]],
    });
    
    OR
    
    this.formGroup = this.fb.group({
      datef: [moment(this.today).toISOString(), [Validators.required]],
      dateng: [{ value: moment(this.today).valueOf() }, [Validators.required]],
    });
    

    Reference : example_in_documentation